<template>
  <div class="routing-rules-management">
    <TopNavigation :showOrganizationSection="false" />
    <div class="page-header">
      <h2>路由规则管理</h2>
    </div>

    <div class="card">
      <div class="toolbar">
        <div class="search-container">
          <div class="input-group">
            <input
              type="text"
              class="input"
              placeholder="搜索角色名称或部门"
              v-model="searchKeyword"
              @keyup.enter="searchRoutingRules"
            />
            <button class="button--submit" @click="searchRoutingRules">
              搜索
            </button>
          </div>
        </div>
        <button class="btn btn-default" @click="openOwnerConfigModal">默认负责人配置</button>
      </div>

      <!-- 路由规则卡片展示 -->
      <div class="rules-container">
        <div v-if="!loading && paginatedRoutingRules.length === 0" class="empty-state">
          <div class="empty-icon">📄</div>
          <div class="empty-text">暂无路由规则数据</div>
        </div>
        
        <div class="loading-indicator" v-if="loading">
          <div class="loading-icon">⏳</div>
          <div class="loading-text">加载中...</div>
        </div>
        
        <div v-else-if="paginatedRoutingRules.length > 0" class="rules-grid">
          <div v-for="row in paginatedRoutingRules" :key="`${row.id || row.roleId}-${row.departmentId}`" class="rule-card">
            <!-- 角色名称和部门信息 -->
            <div class="rule-header">
              <div class="rule-title-section">
                <h3 class="role-name">
                  {{ row.roleName || '未设置' }}
                  <span v-if="row.departmentName && row.departmentName !== '未设置'" class="department-suffix">({{ row.departmentName }})</span>
                </h3>
              </div>
              <div class="action-buttons">
                <button class="edit-btn" @click="handleEdit(row)" title="修改路由规则">
                  <span class="edit-icon">✏️</span>
                </button>
                <button class="manage-btn" @click="openManageModal(row)" title="管理路由规则">
                  <span class="manage-icon">⚙️</span>
                </button>
                <button class="delete-btn" @click="handleDelete(row)" title="删除路由规则">
                  <span class="delete-icon">🗑️</span>
                </button>
              </div>
            </div>
            
            <!-- 用户信息展示 -->
            <div class="user-info-section">
              <h5 class="section-title">分配用户</h5>
              <div class="user-details">
                <div class="user-item">
                  <div class="user-avatar">{{ getUserInitial(row.userName || '未设置') }}</div>
                  <div class="user-info">
                    <div class="user-name">{{ row.userName || '未设置' }}<span v-if="row.userAuthid && row.userAuthid !== '未设置'" class="user-auth-id">({{ row.userAuthid }})</span></div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 统计信息 -->
            <div class="stats-section">
              <div class="stat-item">
                <span class="stat-label">角色:</span>
                <span class="stat-value">{{ row.roleName || '未设置' }}</span>
              </div>
              <div class="stat-item">
                <span class="stat-label">部门:</span>
                <span class="stat-value">{{ row.departmentName || '未设置' }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div v-if="!loading && paginatedRoutingRules.length > 0" class="pagination-container">
        <div class="pagination">
          <button class="btn btn-default" :disabled="currentPage === 1" @click="onPageChange(currentPage - 1)">上一页</button>
          <span class="page-info">第 {{ currentPage }} 页 / 共 {{ totalPages }} 页</span>
          <button class="btn btn-default" :disabled="currentPage >= totalPages" @click="onPageChange(currentPage + 1)">下一页</button>
          <div class="page-size-selector">
            <span>每页显示:</span>
            <select class="select" v-model="pageSize" @change="onPageSizeChange">
              <option :value="5">5条</option>
              <option :value="10">10条</option>
              <option :value="20">20条</option>
              <option :value="50">50条</option>
            </select>
          </div>
        </div>
      </div>
    </div>
  </div>

  <!-- 新增路由规则模态框 -->
  <div v-if="showModal && !isEditMode" class="modal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">{{ isEditMode ? '编辑路由规则' : '新增路由规则' }}</h3>
        <button class="btn btn-default" @click="closeModal">×</button>
      </div>
      <div class="modal-body">
        <!-- 步骤指示器 -->
        <div class="steps-indicator">
          <div class="step" :class="{ active: currentStep === 1 }" @click="goToStep(1)">
            <div class="step-number">1</div>
            <div class="step-text">路由字段配置</div>
          </div>
          <div class="step-arrow">→</div>
          <div class="step" :class="{ active: currentStep === 2 }" @click="currentStep > 1 ? goToStep(2) : undefined">
            <div class="step-number">2</div>
            <div class="step-text">路由规则详情</div>
          </div>
        </div>

        <!-- 路由规则配置 -->
        <div class="step-content">

          <!-- 第二步：路由规则详情 -->
          <div v-if="currentStep === 2" class="form-section">
            <h4 class="section-title">路由规则详情</h4>
            <!-- 角色选择 -->
            <div class="form-grid">
              <div class="form-item">
                <label class="form-label">角色</label>
                <select
                  class="select"
                  v-model="formData.roleId"
                  @change="onRoleChange"
                >
                  <option value="">请选择角色</option>
                  <option v-for="role in roles" :key="role.id || role.roleId" :value="role.id || role.roleId">{{ role.roleName }}</option>
                </select>
                <div v-if="!formData.roleId && showStep2Error" class="error-message">
                  请选择一个角色
                </div>
              </div>
            </div>
            
            <!-- 展示第一步中配置的路由字段 -->
            <div class="form-item mt-4">
              <label class="form-label">路由字段配置（来自第一步）</label>
              <div class="selected-fields">
                <div class="selected-fields-container">
                  <div v-if="step1RouteFields && step1RouteFields.length > 0">
                    <div v-for="field in step1RouteFields" :key="field.id" class="route-field-item">
                      <div class="field-priority">{{ field.priority }}</div>
                      <div class="field-details">
                        <div class="field-name">{{ field.appCnName }}</div>
                        <div class="field-code">{{ field.appEnName }}</div>
                      </div>
                    </div>
                  </div>
                  <div v-else class="empty-fields">
                    暂无配置的路由字段
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 第一步：路由字段配置 -->
          <div v-if="currentStep === 1" class="form-section">
            <h4 class="section-title">路由字段配置</h4>
            <div class="form-item">
              <label class="form-label">可用路由字段</label>
              <div class="available-fields">
                <div class="field-grid">
                <label v-for="field in availableRouteFields" :key="field.id" class="field-card">
                  <div class="field-checkbox">
                    <input
                      type="checkbox"
                      :checked="selectedFieldIds.includes(field.id)"
                      @change="handleFieldSelection(field.id, $event.target.checked)"
                    />
                    <div class="field-info">
                      <div class="field-name">{{ field.appCnName }}</div>
                      <div class="field-code">{{ field.appEnName }}</div>
                      <div v-if="field.description" class="field-description">{{ field.description }}</div>
                    </div>
                  </div>
                </label>
              </div>
              </div>
            </div>

            <div class="form-item">
              <label class="form-label">已选路由字段（可拖动调整优先级）</label>
              <div class="selected-fields">
                <div class="selected-fields-container">
                  <div 
                    v-for="field in selectedRouteFields"
                    :key="field.id"
                    class="route-field-item"
                    draggable="true"
                    @dragstart="handleDragStart(field.id)"
                    @dragover="handleDragOver"
                    @drop="handleDrop(field.id)"
                    :class="{ 'dragging': draggedFieldId === field.id }"
                  >
                    <div class="field-priority">{{ field.priority }}</div>
                    <div class="field-details">
                      <div class="field-name">{{ field.appCnName }}</div>
                      <div class="field-code">{{ field.appEnName }}</div>
                    </div>
                    <button 
                      class="btn btn-danger btn-sm delete-btn"
                      @click="removeSelectedField(field.id)"
                      title="移除此字段"
                    >
                      <i class="icon">×</i>
                    </button>
                    <div class="drag-handle" title="拖动调整优先级">
                      <i class="icon">⋮⋮</i>
                    </div>
                  </div>
                </div>
              </div>
              <div class="drag-tip" v-if="selectedRouteFields.length > 1">
                提示：可拖动已选字段调整优先级
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closeModal">取消</button>
        <button 
          class="btn btn-primary"
          @click="saveRoutingRule"
          :disabled="!formData.roleId || !formData.departmentId || !selectedOwner"
        >
          {{ isEditMode ? '更新' : '确定' }}
        </button>
        <button v-if="currentStep === 1" 
          class="btn btn-primary next-step-btn"
          @click="goToNextStep"
        >
          下一步
        </button>
        <button v-if="currentStep === 2" 
          class="btn btn-default prev-step-btn"
          @click="goToPrevStep"
        >
          上一步
        </button>
      </div>
    </div>
  </div>

  <!-- 编辑路由规则模态框 -->
  <div v-if="showModal && isEditMode" class="modal">
    <div class="modal-content" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">编辑路由规则</h3>
        <button class="btn btn-default" @click="closeModal">×</button>
      </div>
      <div class="modal-body">
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          <div class="form-grid">
            <div class="form-item">
              <label class="form-label">角色</label>
              <div class="readonly-field">
                {{ getRoleName(formData.roleId) || '未设置' }}
              </div>
            </div>
            <div class="form-item">
              <label class="form-label">部门</label>
              <div class="readonly-field">
                {{ getDepartmentName(formData.departmentId) || '未设置' }}
              </div>
            </div>
          </div>
        </div>

        <div class="form-section">
          <h4 class="section-title">负责人配置</h4>
          <div class="form-item">
            <label class="form-label">负责人</label>
            <div class="owner-dropdown-container">
              <div class="custom-dropdown" :class="{ 'disabled': !formData.departmentId }">
                <input
                  type="text"
                  class="dropdown-search"
                  :placeholder="formData.departmentId ? '搜索负责人（用户名/AuthID）' : '请先选择部门'"
                  :disabled="!formData.departmentId"
                  :value="editOwnerSearchKeyword"
                  @input="editOwnerSearchKeyword = $event.target.value"
                  @focus="showEditOwnerDropdown = true"
                  @blur="showEditOwnerDropdown = false"
                  autocomplete="off"
                />
                <div 
                  v-if="showEditOwnerDropdown && formData.departmentId" 
                  class="dropdown-menu"
                >
                  <div 
                    v-for="user in getFilteredDepartmentUsers(formData.departmentId)" 
                    :key="user.id || user.userId || user.authId"
                    class="dropdown-item"
                    @mousedown="selectEditOwner(user)"
                  >
                    <div class="user-info">
                      <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                      <span class="user-id">{{ user.authId || user.id || user.userId }}</span>
                    </div>
                  </div>
                  <div v-if="getFilteredDepartmentUsers(formData.departmentId).length === 0" class="dropdown-item no-results">
                    无匹配结果
                  </div>
                </div>
              </div>
              <div v-if="selectedOwner" class="selected-owners">
                <div class="owner-tag">
                  <span class="owner-name">{{ selectedOwner.userName || selectedOwner.cnName || selectedOwner.name }}</span>
                  <span class="owner-id">({{ selectedOwner.authId || selectedOwner.id || selectedOwner.userId }})</span>
                  <button class="remove-owner" @click="removeEditOwner()">×</button>
                </div>
              </div>
            </div>
            <div v-if="!selectedOwner && showOwnerError" class="error-message">
              请选择一个负责人
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closeModal">取消</button>
        <button 
          class="btn btn-primary"
          @click="saveRoutingRule"
          :disabled="!formData.roleId || !formData.departmentId || !selectedOwner"
        >
          更新
        </button>
      </div>
    </div>
  </div>

  <!-- 默认负责人配置模态框 -->
  <div v-if="ownerConfigModalVisible" class="modal">
    <div class="modal-content large-modal" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">默认负责人配置</h3>
        <button class="btn btn-default" @click="closeOwnerConfigModal">×</button>
      </div>
      <div class="modal-body">
        <div class="form-section">
          <h4 class="section-title">基本信息</h4>
          <div class="form-item">
            <label class="form-label">角色</label>
            <select
              class="select"
              v-model="ownerConfigFormData.roleId"
              @change="onOwnerConfigRoleChange"
            >
              <option value="">请选择角色</option>
              <option v-for="role in roles" :key="role.id || role.roleId" :value="role.id || role.roleId">{{ role.roleName }}</option>
            </select>
            <div v-if="!ownerConfigFormData.roleId && ownerConfigShowBasicInfoError" class="error-message">
              请选择一个角色
            </div>
          </div>
        </div>

        <div class="form-section">
          <h4 class="section-title">部门负责人配置</h4>
          <div class="department-config">
            <div class="department-header">
              <button 
                class="btn btn-primary" 
                @click="addDepartmentRow"
                :disabled="!canAddMoreDepartments"
              >
                添加部门
                <span v-if="ownerConfigFormData.roleId && selectedRoleDepartments.length > 0" class="department-count">
                  ({{ ownerConfigDepartmentRows.length }}/{{ selectedRoleDepartments.length }})
                </span>
              </button>
            </div>
            
            <div v-if="ownerConfigDepartmentRows.length === 0" class="empty-departments">
              暂无部门配置，请点击"添加部门"按钮添加
            </div>
            
            <div v-for="(row, index) in ownerConfigDepartmentRows" :key="index" class="department-row">
              <div class="department-selection">
                <label class="form-label">部门</label>
                <div class="department-dropdown-container">
                  <div class="custom-dropdown">
                    <input
                       type="text"
                       class="dropdown-search"
                       :placeholder="getDepartmentDisplayName(index) || '搜索部门名称'"
                       :value="getDepartmentDisplayName(index) || getDepartmentSearchKeyword(index)"
                       @input="setDepartmentSearchKeyword(index, $event.target.value)"
                       @focus="showDepartmentDropdown(index)"
                       @blur="hideDepartmentDropdown(index)"
                       autocomplete="off"
                       :readonly="!!getDepartmentDisplayName(index)"
                     />
                    <div 
                      v-if="isDepartmentDropdownVisible(index)" 
                      class="dropdown-menu"
                    >
                      <div 
                        v-for="dept in getFilteredAvailableDepartments(index)" 
                        :key="dept.deptId"
                        class="dropdown-item"
                        @mousedown="selectDepartmentFromSearch(index, dept)"
                      >
                        <div class="department-info">
                          <span class="department-name">{{ dept.deptName }}</span>
                        </div>
                      </div>
                      <div v-if="getFilteredAvailableDepartments(index).length === 0" class="dropdown-item no-results">
                        无匹配结果
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="owner-selection">
                <label class="form-label">负责人</label>
                <div class="owner-dropdown-container">
                  <div class="custom-dropdown" :class="{ 'disabled': !row.departmentId }">
                    <input
                        type="text"
                        class="dropdown-search"
                        :placeholder="row.departmentId ? '搜索负责人（用户名/AuthID）' : '请先选择部门'"
                        :disabled="!row.departmentId"
                        :value="getOwnerSearchKeyword(index)"
                        @input="setOwnerSearchKeyword(index, $event.target.value)"
                        @focus="showOwnerDropdown(index)"
                        @blur="hideOwnerDropdown(index)"
                        autocomplete="off"
                      />
                    <div 
                      v-if="isOwnerDropdownVisible(index) && row.departmentId" 
                      class="dropdown-menu"
                    >
                      <div 
                        v-for="user in getFilteredAvailableUsers(row.departmentId, index)" 
                        :key="user.id || user.userId || user.authId"
                        class="dropdown-item"
                        @mousedown="selectOwnerFromSearch(index, user)"
                      >
                        <div class="user-info">
                          <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                          <span class="user-id">{{ user.authId || user.id || user.userId }}</span>
                        </div>
                      </div>
                      <div v-if="getFilteredAvailableUsers(row.departmentId, index).length === 0" class="dropdown-item no-results">
                        无匹配结果
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="row.owners && row.owners.length > 0" class="selected-owners">
                  <div class="owners-header">
                    <span class="owners-count">已选择 {{ row.owners.length }} 个负责人</span>
                    <button class="btn btn-danger btn-sm" @click="removeAllOwnerConfigOwners(index)">清空所有</button>
                  </div>
                  <div class="owners-list">
                    <div v-for="(owner, ownerIndex) in row.owners" :key="owner.id || owner.userId || owner.authId" class="owner-tag">
                      <span class="owner-name">{{ owner.userName || owner.cnName || owner.name }}</span>
                      <button class="btn btn-danger btn-xs" @click="removeOwnerConfigOwner(index, ownerIndex)">×</button>
                    </div>
                  </div>
                </div>
              </div>
              
              <div class="row-actions">
                <button class="btn btn-danger" @click="removeDepartmentRow(index)">删除</button>
              </div>
            </div>
          </div>
          
          <div v-if="ownerConfigDepartmentRows.length > 0 && !allOwnerConfigDepartmentsHaveOwners() && ownerConfigShowOwnerError" class="error-message">
            请为所有部门选择负责人
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closeOwnerConfigModal">取消</button>
        <button 
          class="btn btn-primary"
          @click="saveOwnerConfig"
          :disabled="!ownerConfigFormData.roleId || ownerConfigDepartmentRows.length === 0 || !allOwnerConfigDepartmentsHaveOwners()"
        >
          保存配置
        </button>
      </div>
    </div>
  </div>

  <!-- 管理角色配置模态框 -->
  <div v-if="manageModalVisible" class="modal">
    <div class="modal-content large-modal" @click.stop>
      <div class="modal-header">
        <h3 class="modal-title">管理角色配置</h3>
        <button class="btn btn-default" @click="closeManageModal">×</button>
      </div>
      <div class="modal-body">
        <!-- 基本信息展示 -->
        <div v-if="currentRoleData" class="form-section">
          <h4 class="section-title">基本信息</h4>
          <div class="form-grid">
            <div class="form-item">
              <label class="form-label">角色</label>
              <div class="readonly-field">
                {{ currentRoleData.roleName || '未设置' }}
              </div>
            </div>
            <div class="form-item">
              <label class="form-label">部门</label>
              <div class="readonly-field">
                {{ getDepartmentName(currentRoleData.departmentId) || '未设置' }}
              </div>
            </div>
          </div>
        </div>

        <!-- 字段配置信息 -->
        <div class="form-section">
          <h4 class="section-title">字段配置</h4>
          <div v-if="currentRoleFieldConfigs && currentRoleFieldConfigs.length > 0" class="field-config-hint">
            <p class="config-hint-text">请为以下字段配置相应的值：</p>
            <div class="field-names">
              <span v-for="(fieldName, index) in currentRoleFieldConfigs" :key="index" class="field-name-tag">
                {{ fieldName }}
              </span>
            </div>
          </div>
          <div class="dynamic-field-configs">
            <!-- 动态配置项列表 -->
            <div v-for="(configItem, index) in dynamicFieldConfigs" :key="configItem.id" class="dynamic-config-item">
              <div class="config-card">
                <div class="config-header">
                  <span class="config-index">配置 {{ index + 1 }}</span>
                  <button 
                    class="remove-config-btn" 
                    @click="removeDynamicConfig(index)"
                    :disabled="dynamicFieldConfigs.length <= 1"
                  >
                    ×
                  </button>
                </div>
                
                <div class="config-content">
                  <!-- 配置项字段值 -->
                  <div class="field-group">
                    <label class="field-label">字段配置:
                      <span v-if="currentRoleFieldConfigs && currentRoleFieldConfigs.length > 0" class="field-hint">
                        (可选字段：{{ currentRoleFieldConfigs.join('、') }})
                      </span>
                    </label>
                    <div class="field-values-container">
                      <div v-for="(fieldConfig, fieldIndex) in configItem.fieldConfigs" :key="fieldIndex" class="field-config-row">
                        <!-- 字段选择下拉框 -->
                        <select 
                          class="field-select"
                          v-model="configItem.fieldConfigs[fieldIndex].fieldName"
                          @change="updateFieldConfig(configItem.id, fieldIndex, 'fieldName', $event.target.value)"
                        >
                          <option value="">请选择字段</option>
                          <!-- 显示当前已选择的字段（如果有） -->
                          <option 
                            v-if="configItem.fieldConfigs[fieldIndex].fieldName && !getAvailableFieldsForConfig(configItem.id, fieldIndex).includes(configItem.fieldConfigs[fieldIndex].fieldName)"
                            :value="configItem.fieldConfigs[fieldIndex].fieldName"
                          >
                            {{ configItem.fieldConfigs[fieldIndex].fieldName }}
                          </option>
                          <!-- 显示可用的字段选项 -->
                          <option 
                            v-for="(fieldName, index) in getAvailableFieldsForConfig(configItem.id, fieldIndex)" 
                            :key="index" 
                            :value="fieldName"
                          >
                            {{ fieldName }}
                          </option>
                        </select>
                        
                        <!-- 字段值输入框 -->
                        <input 
                          type="text" 
                          class="field-value-input"
                          :placeholder="configItem.fieldConfigs[fieldIndex].fieldName ? `请输入${configItem.fieldConfigs[fieldIndex].fieldName}的值` : '请先选择字段'"
                          v-model="configItem.fieldConfigs[fieldIndex].fieldValue"
                          @input="updateFieldConfig(configItem.id, fieldIndex, 'fieldValue', $event.target.value)"
                          :disabled="!configItem.fieldConfigs[fieldIndex].fieldName"
                        />
                        
                        <!-- 删除按钮 -->
                        <button 
                          v-if="configItem.fieldConfigs.length > 1"
                          class="remove-field-btn" 
                          @click="removeFieldConfig(configItem.id, fieldIndex)"
                        >
                          ×
                        </button>
                      </div>
                      <button class="add-field-btn" @click="addFieldConfig(configItem.id)">
                        + 添加字段配置
                      </button>
                    </div>
                  </div>
                  
                  <!-- 处理人选择 -->
                  <div class="field-group">
                    <label class="field-label">处理人:</label>
                    <div class="processor-selector">
                      <div class="custom-dropdown">
                        <input
                          type="text"
                          class="dropdown-search"
                          :placeholder="currentRoleData?.departmentId ? '选择处理人' : '请先选择部门'"
                          :disabled="!currentRoleData?.departmentId"
                          :value="configItem.processorSearchKeyword || ''"
                          @input="updateDynamicProcessorSearch(configItem.id, $event.target.value)"
                          @focus="showDynamicProcessorDropdown[configItem.id] = true"
                          @blur="hideDynamicProcessorDropdown(configItem.id)"
                          autocomplete="off"
                        />
                        <div 
                          v-if="showDynamicProcessorDropdown[configItem.id] && currentRoleData?.departmentId" 
                          class="dropdown-menu"
                        >
                          <div 
                            v-for="user in getFilteredDynamicProcessorUsers(configItem.id)" 
                            :key="user.id || user.userId || user.authId"
                            class="dropdown-item"
                            @mousedown="selectDynamicProcessor(configItem.id, user)"
                          >
                            <div class="user-info">
                              <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                              <span class="user-id">{{ user.authId || user.id || user.userId }}</span>
                            </div>
                          </div>
                          <div v-if="getFilteredDynamicProcessorUsers(configItem.id).length === 0" class="dropdown-item no-results">
                            无匹配结果
                          </div>
                        </div>
                      </div>
                      <div v-if="configItem.processor" class="selected-processor">
                        <span class="processor-name">{{ configItem.processor.userName || configItem.processor.cnName || configItem.processor.name }}</span>
                        <button class="remove-processor" @click="removeDynamicProcessor(configItem.id)">×</button>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            <!-- 添加配置按钮 -->
            <div class="add-config-section">
              <button class="add-config-btn" @click="addDynamicConfig">
                <span class="add-icon">+</span>
                添加新配置
              </button>
            </div>
          </div>
        </div>

        <!-- 负责人配置 -->
        <div class="form-section">
          <h4 class="section-title">负责人配置</h4>
          <div class="form-item">
            <label class="form-label">负责人</label>
            <div class="owner-dropdown-container">
              <div class="custom-dropdown" :class="{ 'disabled': !currentRoleData?.departmentId }">
                <input
                  type="text"
                  class="dropdown-search"
                  :placeholder="currentRoleData?.departmentId ? '搜索负责人（用户名/AuthID）' : '请先选择部门'"
                  :disabled="!currentRoleData?.departmentId"
                  :value="manageOwnerSearchKeyword"
                  @input="manageOwnerSearchKeyword = $event.target.value"
                  @focus="showManageOwnerDropdown = true"
                  @blur="showManageOwnerDropdown = false"
                  autocomplete="off"
                />
                <div 
                  v-if="showManageOwnerDropdown && currentRoleData?.departmentId" 
                  class="dropdown-menu"
                >
                  <div 
                    v-for="user in getFilteredManageDepartmentUsers()" 
                    :key="user.id || user.userId || user.authId"
                    class="dropdown-item"
                    @mousedown="selectManageOwner(user)"
                  >
                    <div class="user-info">
                      <span class="user-name">{{ user.userName || user.cnName || user.name }}</span>
                      <span class="user-id">{{ user.authId || user.id || user.userId }}</span>
                    </div>
                  </div>
                  <div v-if="getFilteredManageDepartmentUsers().length === 0" class="dropdown-item no-results">
                    无匹配结果
                  </div>
                </div>
              </div>
              <div v-if="selectedOwner" class="selected-owners">
                <div class="owner-tag">
                  <span class="owner-name">{{ selectedOwner.userName || selectedOwner.cnName || selectedOwner.name }}</span>
                  <span class="owner-id">({{ selectedOwner.authId || selectedOwner.id || selectedOwner.userId }})</span>
                  <button class="remove-owner" @click="removeManageOwner()">×</button>
                </div>
              </div>
            </div>
            <div v-if="!selectedOwner && showManageOwnerError" class="error-message">
              请选择一个负责人
            </div>
          </div>
        </div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-default" @click="closeManageModal">关闭</button>
        <button 
          class="btn btn-secondary"
          @click="saveManageConfig"
          :disabled="!selectedOwner"
        >
          保存配置
        </button>
        <button 
          class="btn btn-primary"
          @click="submitRoutingRule"
          :disabled="!selectedOwner || !validateSubmitData()"
        >
          提交路由规则
        </button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import TopNavigation from '../components/TopNavigation.vue'
import { getRoleConfigs, createRoleConfig, updateRoleConfig, deleteRoleConfig, getRoleConfigById } from '../services/roleDepartmentUserService'
import { getRoleDepartmentUsers, createRoleDepartmentUser, updateRoleDepartmentUser, deleteRoleDepartmentUser } from '../services/roleDepartmentUserService'
import { createRoutingRule } from '../services/roleRouteService'
import departmentService from '../services/departmentService'
import userService from '../services/userService'

// 数据状态
const routingRulesData = ref([]);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const searchKeyword = ref('');

// 角色、部门、用户和路由字段数据
const roles = ref([]);
const departments = ref([]);
const routeFields = ref([]);
const users = ref([]);
const roleDepartmentUsers = ref([]);

// 模态框相关状态
const showModal = ref(false);
const ownerConfigModalVisible = ref(false);
const isEditMode = ref(false);
const currentRuleId = ref(null);
const formData = ref({
  roleId: '',
  routeFields: []
});

// 默认负责人配置模态框数据
const ownerConfigFormData = ref({
  roleId: '',
  departmentRows: []
});
const currentStep = ref(1);
const step1RouteFields = ref([]);

// 拖放相关状态
const draggedFieldId = ref(null);
const selectedFieldIds = ref([]);
const selectedDepartments = ref([]); // 存储选中的部门
const departmentOwners = ref(new Map()); // 存储部门ID和负责人的映射
const departmentSearchKeywords = ref(new Map()); // 存储每个部门的搜索关键词
const activeDepartmentId = ref(null); // 当前活动的部门ID（用于显示下拉框）
const showBasicInfoError = ref(false);
const showOwnerError = ref(false);
const roleSearchKeyword = ref('');
const showStep2Error = ref(false);
const showStep2OwnerError = ref(false);

// 默认负责人配置模态框相关状态
const ownerConfigDepartmentRows = ref([]);
const ownerConfigShowBasicInfoError = ref(false);
const ownerConfigShowOwnerError = ref(false);
const selectedRoleDepartments = ref([]); // 存储当前选择角色的部门配置
const departmentUsers = ref(new Map()); // 存储每个部门的用户数据，key为部门ID，value为用户数组
const ownerSearchKeywords = ref(new Map()); // 存储每个部门行的搜索关键词
const ownerDropdownVisible = ref(new Map()); // 存储每个部门行的下拉框显示状态 // 存储每个部门行的部门搜索关键词
const departmentDropdownVisible = ref(new Map()); // 存储每个部门行的部门下拉框显示状态

// 管理角色配置模态框相关状态
const manageModalVisible = ref(false);
const currentRoleData = ref(null);
const roleFieldConfigs = ref([]);
const selectedOwner = ref(null);
const ownerSearchKeyword = ref('');
const showOwnerDropdownOld = ref(false);

// 从API获取角色数据
const fetchRoles = async () => {
  try {
    const response = await getRoleConfigs();
    roles.value = response.data || [];
    console.log('获取到的角色数据:', roles.value);
  } catch (error) {
    console.error('获取角色数据失败:', error);
  }
};

// 从API获取部门数据
const fetchDepartments = async () => {
  try {
    const response = await departmentService.getDepartments();
    departments.value = response.data || [];
  } catch (error) {
    console.error('获取部门数据失败:', error);
    departments.value = [];
  }
};

// 从API获取用户数据
const fetchUsers = async () => {
  try {
    const response = await userService.getUsers();
    users.value = response.data || [];
  } catch (error) {
    console.error('获取用户数据失败:', error);
  }
};

// 从API获取路由字段数据
const fetchRouteFields = async () => {
  try {
    const mockRouteFields = [];
    routeFields.value = mockRouteFields;
  } catch (error) {
    console.error('获取路由字段数据失败:', error);
  }
};

// 获取角色部门用户数据
const fetchRoleDepartmentUsers = async () => {
  try {
    // 构建分页参数
    const params = {
      page: currentPage.value - 1, // 后端通常从0开始计数
      size: pageSize.value
    };
    
    // 添加搜索参数
    if (searchKeyword.value.trim()) {
      params.search = searchKeyword.value.trim();
    }
    
    const response = await getRoleDepartmentUsers(params);
    const userData = response.data?.content || response.data || [];
    total.value = response.data?.totalElements || response.data?.total || userData.length;
    roleDepartmentUsers.value = userData;
  } catch (error) {
    console.error('获取角色部门用户数据失败:', error);
  }
};

// 处理页码变化
const onPageChange = (newPage) => {
  currentPage.value = newPage;
  fetchRoleDepartmentUsers();
};

// 处理分页大小变化
const onPageSizeChange = () => {
  currentPage.value = 1;
  fetchRoleDepartmentUsers();
};

// 获取角色字段配置信息
const fetchRoleFieldConfigs = async (roleId) => {
  try {
    const response = await getRoleConfigById(roleId);
    const roleConfig = response.data || {};
    let fieldConfigs = [];
    
    // 优先使用fieldPriorities字段
    if (roleConfig.fieldPriorities) {
      try {
        let priorities = [];
        if (typeof roleConfig.fieldPriorities === 'string') {
          priorities = JSON.parse(roleConfig.fieldPriorities);
        } else if (Array.isArray(roleConfig.fieldPriorities)) {
          priorities = roleConfig.fieldPriorities;
        }
        
        if (Array.isArray(priorities) && priorities.length > 0) {
          fieldConfigs = priorities.map((fieldName, index) => ({
            name: fieldName,
            code: `field_${index}`,
            description: `${fieldName}字段配置`
          }));
        }
      } catch (error) {
        console.error('解析fieldPriorities失败:', error);
      }
    }
    
    // 如果fieldPriorities没有数据，则使用fieldConfig
    if (fieldConfigs.length === 0 && roleConfig.fieldConfig) {
      if (Array.isArray(roleConfig.fieldConfig)) {
        fieldConfigs = roleConfig.fieldConfig;
      } else if (typeof roleConfig.fieldConfig === 'object') {
        fieldConfigs = [roleConfig.fieldConfig];
      } else if (typeof roleConfig.fieldConfig === 'string') {
        try {
          const parsed = JSON.parse(roleConfig.fieldConfig);
          if (parsed.fields && Array.isArray(parsed.fields)) {
            fieldConfigs = parsed.fields.map((fieldName, index) => ({
              name: fieldName,
              code: `field_${index}`,
              description: `${fieldName}字段配置`
            }));
          } else {
            fieldConfigs = Array.isArray(parsed) ? parsed : [parsed];
          }
        } catch (error) {
          console.error('解析fieldConfig JSON失败:', error);
          fieldConfigs = [];
        }
      }
    }
    
    // 其他备用字段
    if (fieldConfigs.length === 0) {
      if (roleConfig.fieldConfigs) {
        fieldConfigs = roleConfig.fieldConfigs;
      } else if (roleConfig.fieldSettings) {
        fieldConfigs = roleConfig.fieldSettings;
      } else if (roleConfig.configs) {
        fieldConfigs = roleConfig.configs;
      } else {
        const routeFieldInfo = routeFields.value.find(f => f.id === roleId);
        if (routeFieldInfo) {
          fieldConfigs = [{
            name: routeFieldInfo.appCnName,
            code: routeFieldInfo.appEnName,
            description: routeFieldInfo.description
          }];
        } else {
          fieldConfigs = [{
            name: '默认字段',
            code: 'defaultField',
            description: '这是一个示例字段配置'
          }];
        }
      }
    }
    
    roleFieldConfigs.value = fieldConfigs;
  } catch (error) {
    console.error('获取角色字段配置失败:', error);
    roleFieldConfigs.value = [{
      name: '默认字段',
      code: 'defaultField',
      description: '这是一个示例字段配置'
    }];
  }
};

// 一次性获取所有需要的数据
const fetchAllData = async () => {
  loading.value = true;
  try {
    await Promise.all([
      fetchRoles(),
      fetchDepartments(),
      fetchUsers(),
      fetchRouteFields(),
      fetchRoleDepartmentUsers()
    ]);
  } catch (error) {
    console.error('获取数据失败:', error);
  } finally {
    loading.value = false;
  }
};

// 监听角色部门用户数据变化并更新总数
watch(roleDepartmentUsers, (newValue) => {
  total.value = newValue.length;
}, { immediate: true });

// 根据用户ID获取用户名称
const getUserName = (id) => {
  const user = users.value.find(u => u.id === id || u.userId === id)
  return user ? user.userName : '未设置'
};

// 可用的路由字段
const availableRouteFields = computed(() => {
  return routeFields.value.filter(field => !selectedFieldIds.value.includes(field.id))
});

// 已选择的路由字段（部门默认为第一优先级）
const selectedRouteFields = computed(() => {
  const departmentField = {
    id: 'dept',
    appCnName: '部门',
    appEnName: 'Department',
    priority: 1
  }
  
  const userFields = selectedFieldIds.value.map((fieldId, index) => {
    const field = routeFields.value.find(f => f.id === fieldId)
    return field ? {
      ...field,
      priority: index + 2
    } : null
  }).filter(Boolean)
  
  return [departmentField, ...userFields]
});

// 计算总页数
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value) || 1;
});

// 计算当前页显示的角色部门用户（后端分页）
const filteredRoutingRules = computed(() => {
  return roleDepartmentUsers.value;
});

// 计算当前页显示的角色部门用户（后端分页）
const paginatedRoutingRules = computed(() => {
  return filteredRoutingRules.value;
});

// 根据选择的角色过滤部门列表，并排除已选择的部门
const filteredDepartmentsForRole = computed(() => {
  console.log('计算过滤部门列表:', {
    roleId: ownerConfigFormData.value.roleId,
    selectedRoleDepartments: selectedRoleDepartments.value,
    allDepartments: departments.value
  });
  
  let availableDepartments = [];
  
  if (!ownerConfigFormData.value.roleId || selectedRoleDepartments.value.length === 0) {
    console.log('返回所有部门，因为没有选择角色或角色没有部门配置');
    availableDepartments = departments.value;
  } else {
    // 根据角色配置的部门ID过滤部门列表
    const roleDepartmentIds = selectedRoleDepartments.value.map(dept => dept.id || dept.deptId);
    console.log('角色配置的部门ID:', roleDepartmentIds);
    availableDepartments = departments.value.filter(dept => roleDepartmentIds.includes(dept.deptId));
    console.log('角色过滤后的部门:', availableDepartments);
  }
  
  // 排除已经选择的部门
  const selectedDepartmentIds = ownerConfigDepartmentRows.value.map(row => row.departmentId).filter(Boolean);
  console.log('已选择的部门ID:', selectedDepartmentIds);
  
  const finalFiltered = availableDepartments.filter(dept => !selectedDepartmentIds.includes(dept.deptId));
  console.log('最终过滤后的部门:', finalFiltered);
  
  return finalFiltered;
});

// 判断是否可以继续添加部门
const canAddMoreDepartments = computed(() => {
  // 如果没有选择角色，不能添加部门
  if (!ownerConfigFormData.value.roleId) {
    return false;
  }
  
  // 如果没有角色配置的部门信息，允许添加（兼容旧数据）
  if (selectedRoleDepartments.value.length === 0) {
    return true;
  }
  
  // 已添加的部门数量不能超过角色配置的部门总数
  return ownerConfigDepartmentRows.value.length < selectedRoleDepartments.value.length;
});

// 过滤用户
const filteredUsers = computed(() => {
  if (!ownerSearchKeyword.value.trim()) {
    return users.value;
  }
  const keyword = ownerSearchKeyword.value.toLowerCase();
  return users.value.filter(user => 
    user.userName.toLowerCase().includes(keyword)
  );
});

// 当前角色的字段配置名称数组
const currentRoleFieldConfigs = computed(() => {
  if (!roleFieldConfigs.value || roleFieldConfigs.value.length === 0) {
    return [];
  }
  return roleFieldConfigs.value.map(config => config.name || config.fieldName || config.code || '未知字段');
});

// 获取指定配置项可用的字段选项（同一配置项内不同字段配置行之间字段不重复）
const getAvailableFieldsForConfig = (configId, currentFieldIndex = null) => {
  if (!currentRoleFieldConfigs.value || currentRoleFieldConfigs.value.length === 0) {
    return [];
  }
  
  // 获取当前配置项
  const currentConfig = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (!currentConfig) {
    return currentRoleFieldConfigs.value;
  }
  
  // 获取当前配置项中其他字段配置行已选择的字段名称
  const selectedFieldNames = new Set();
  
  if (currentConfig.fieldConfigs) {
    currentConfig.fieldConfigs.forEach((fieldConfig, index) => {
      if (currentFieldIndex === null || index !== currentFieldIndex) {
        if (fieldConfig.fieldName && fieldConfig.fieldName.trim()) {
          selectedFieldNames.add(fieldConfig.fieldName);
        }
      }
    });
  }
  
  // 返回未被当前配置项中其他字段配置行选择的字段
  return currentRoleFieldConfigs.value.filter(fieldName => !selectedFieldNames.has(fieldName));
};

// 搜索路由规则
const searchRoutingRules = () => {
  currentPage.value = 1;
  fetchRoleDepartmentUsers();
};

// 显示新增模态框
const showAddModal = () => {
  isEditMode.value = false;
  currentRuleId.value = null;
  formData.value = {
    roleId: '',
    routeFields: []
  };
  selectedFieldIds.value = [];
  roleSearchKeyword.value = '';
  selectedDepartments.value = [];
  departmentOwners.value.clear();
  departmentSearchKeywords.value.clear();
  activeDepartmentId.value = null;
  
  showBasicInfoError.value = false;
  showOwnerError.value = false;
  showStep2Error.value = false;
  showStep2OwnerError.value = false;
  currentStep.value = 1;
  step1RouteFields.value = [];
  showModal.value = true;
};

// 显示默认负责人配置模态框
const openOwnerConfigModal = async () => {
  ownerConfigFormData.value = {
    roleId: '',
    departmentRows: []
  };
  ownerConfigDepartmentRows.value = [];
  ownerConfigShowBasicInfoError.value = false;
  ownerConfigShowOwnerError.value = false;
  
  if (departments.value.length === 0) {
    await fetchDepartments();
  }
  
  await fetchUsers();
  
  ownerConfigModalVisible.value = true;
};

// 显示编辑模态框
const handleEdit = async (route) => {
  isEditMode.value = true;
  currentRuleId.value = route.id || `${route.roleId}-${route.departmentId}`;
  
  // 确保roleId字段与角色选择下拉框的value匹配
  // 优先使用roleConfigId，如果没有则使用roleId
  const roleIdValue = route.roleConfigId || route.roleId || '';
  
  formData.value = {
    roleId: roleIdValue,
    departmentId: route.departmentId || '',
    routeFields: route.routeFields || []
  };
  
  showBasicInfoError.value = false;
  showOwnerError.value = false;
  
  if (route.userId) {
    const user = users.value.find(u => u.id === route.userId || u.userId === route.userId);
    selectedOwner.value = user || null;
  } else {
    selectedOwner.value = null;
  }
  
  // 重置编辑模态框的搜索状态
  editOwnerSearchKeyword.value = '';
  showEditOwnerDropdown.value = false;
  
  // 如果有部门ID，确保获取该部门的用户数据
  if (route.departmentId && !departmentUsers.value.has(route.departmentId)) {
    try {
      const response = await userService.getUsersByDepartment(route.departmentId);
      let userData = [];
      if (response && response.data) {
        userData = Array.isArray(response.data) ? response.data : [response.data];
      } else if (response && Array.isArray(response)) {
        userData = response;
      }
      departmentUsers.value.set(route.departmentId, userData);
    } catch (error) {
      console.error('获取部门用户失败:', error);
      departmentUsers.value.set(route.departmentId, users.value || []);
    }
  }
  
  showModal.value = true;
};

// 获取角色名称
const getRoleName = (roleId) => {
  if (!roleId) return '';
  const role = roles.value.find(r => (r.id || r.roleId) === roleId);
  return role ? role.roleName : '';
};

// 获取部门名称
const getDepartmentName = (departmentId) => {
  if (!departmentId) return '';
  const dept = departments.value.find(d => d.deptId === departmentId);
  return dept ? dept.deptName : '';
};

// 编辑模态框的负责人搜索关键词
const editOwnerSearchKeyword = ref('');
const showEditOwnerDropdown = ref(false);

// 获取过滤后的部门用户（用于编辑模态框）
const getFilteredDepartmentUsers = (departmentId) => {
  if (!departmentId) return [];
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(departmentId) || [];
  const searchKeyword = editOwnerSearchKeyword.value.toLowerCase().trim();
  
  if (!searchKeyword) {
    return deptUsers;
  }
  
  return deptUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase();
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase();
    
    return userName.includes(searchKeyword) || authId.includes(searchKeyword);
  });
};

// 选择编辑模态框的负责人
const selectEditOwner = (user) => {
  selectedOwner.value = user;
  editOwnerSearchKeyword.value = '';
  showEditOwnerDropdown.value = false;
};

// 移除编辑模态框的负责人
const removeEditOwner = () => {
  selectedOwner.value = null;
  editOwnerSearchKeyword.value = '';
};

// 显示管理模态框
const openManageModal = async (route) => {
  currentRoleData.value = route;
  
  // 重置字段配置状态
  resetFieldConfigStates();
  
  if (route.roleId || route.roleConfigId) {
    await fetchRoleFieldConfigs(route.roleId || route.roleConfigId);
  }
  
  if (route.userId) {
    const user = users.value.find(u => u.id === route.userId || u.userId === route.userId);
    selectedOwner.value = user || null;
  } else {
    selectedOwner.value = null;
  }
  
  // 重置管理模态框的搜索状态
  manageOwnerSearchKeyword.value = '';
  showManageOwnerDropdown.value = false;
  showManageOwnerError.value = false;
  
  // 如果有部门ID，确保获取该部门的用户数据
  if (route.departmentId && !departmentUsers.value.has(route.departmentId)) {
    try {
      const response = await userService.getUsersByDepartment(route.departmentId);
      let userData = [];
      if (response && response.data) {
        userData = Array.isArray(response.data) ? response.data : [response.data];
      } else if (response && Array.isArray(response)) {
        userData = response;
      }
      departmentUsers.value.set(route.departmentId, userData);
    } catch (error) {
      console.error('获取部门用户失败:', error);
      departmentUsers.value.set(route.departmentId, users.value || []);
    }
  }
  
  // 加载现有的字段配置数据（如果有的话）
  if (route.fieldConfigData) {
    loadFieldConfigData(route.fieldConfigData);
  }
  
  // 初始化动态配置
  if (route.dynamicConfigData) {
    await loadDynamicConfigData(route.dynamicConfigData);
  } else {
    await initializeDynamicConfigs();
  }
  
  manageModalVisible.value = true;
};

// 管理模态框的负责人搜索关键词
const manageOwnerSearchKeyword = ref('');
const showManageOwnerDropdown = ref(false);
const showManageOwnerError = ref(false);

// 字段值配置相关状态
const fieldValues = ref({});
const fieldProcessors = ref({});
const fieldProcessorSearchKeywords = ref({});
const showFieldProcessorDropdown = ref({});
const fieldProcessorErrors = ref({});

// 动态字段配置相关状态
const dynamicFieldConfigs = ref([]);
const showDynamicProcessorDropdown = ref({});
let dynamicConfigIdCounter = 0;

// 初始化动态配置
const initializeDynamicConfigs = async () => {
  // 确保roleFieldConfigs有数据
  if (roleFieldConfigs.value.length === 0 && currentRoleData.value?.roleId) {
    await fetchRoleFieldConfigs(currentRoleData.value.roleId);
  }
  
  dynamicFieldConfigs.value = [{
    id: ++dynamicConfigIdCounter,
    fieldConfigs: [{ fieldName: '', fieldValue: '' }], // 字段配置数组
    processor: null, // 单个处理人
    processorSearchKeyword: ''
  }];
};

// 添加动态配置
const addDynamicConfig = async () => {
  // 确保roleFieldConfigs有数据
  if (roleFieldConfigs.value.length === 0 && currentRoleData.value?.roleId) {
    await fetchRoleFieldConfigs(currentRoleData.value.roleId);
  }
  
  dynamicFieldConfigs.value.push({
    id: ++dynamicConfigIdCounter,
    fieldConfigs: [{ fieldName: '', fieldValue: '' }], // 字段配置数组
    processor: null, // 单个处理人
    processorSearchKeyword: ''
  });
};

// 添加字段配置到指定配置项
const addFieldConfig = (configId) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem) {
    configItem.fieldConfigs.push({ fieldName: '', fieldValue: '' });
  }
};

// 移除指定配置项的字段配置
const removeFieldConfig = (configId, fieldIndex) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem && configItem.fieldConfigs.length > 1) {
    configItem.fieldConfigs.splice(fieldIndex, 1);
  }
};

// 更新字段配置
const updateFieldConfig = (configId, fieldIndex, property, value) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem && configItem.fieldConfigs[fieldIndex]) {
    configItem.fieldConfigs[fieldIndex][property] = value;
  }
};

// 兼容旧方法名（保持向后兼容）
const addFieldValue = addFieldConfig;
const removeFieldValue = removeFieldConfig;
const updateFieldValue = (configId, fieldIndex, value) => {
  updateFieldConfig(configId, fieldIndex, 'fieldValue', value);
};

// 移除动态配置
const removeDynamicConfig = (index) => {
  if (dynamicFieldConfigs.value.length > 1) {
    const configItem = dynamicFieldConfigs.value[index];
    // 清理下拉框状态
    delete showDynamicProcessorDropdown.value[configItem.id + '_processor'];
    dynamicFieldConfigs.value.splice(index, 1);
  }
};

// 更新动态配置处理员工搜索关键词
const updateDynamicProcessorSearch = (configId, value) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem) {
    configItem.processorSearchKeyword = value;
  }
};

// 隐藏动态配置处理员工下拉框
const hideDynamicProcessorDropdown = (dropdownKey) => {
  setTimeout(() => {
    showDynamicProcessorDropdown.value[dropdownKey] = false;
  }, 200);
};

// 获取过滤后的动态配置处理员工用户
const getFilteredDynamicProcessorUsers = (configId) => {
  if (!currentRoleData.value?.departmentId) return [];
  
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (!configItem) return [];
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(currentRoleData.value.departmentId) || [];
  const searchKeyword = (configItem.processorSearchKeyword || '').toLowerCase().trim();
  
  if (!searchKeyword) {
    return deptUsers;
  }
  
  return deptUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase();
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase();
    
    return userName.includes(searchKeyword) || authId.includes(searchKeyword);
  });
};

// 选择动态配置处理员工
const selectDynamicProcessor = (configId, user) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem) {
    configItem.processor = user;
    configItem.processorSearchKeyword = '';
    showDynamicProcessorDropdown.value[configId + '_processor'] = false;
  }
};

// 移除动态配置处理员工
const removeDynamicProcessor = (configId) => {
  const configItem = dynamicFieldConfigs.value.find(item => item.id === configId);
  if (configItem) {
    configItem.processor = null;
    configItem.processorSearchKeyword = '';
  }
};

// 重置动态配置状态
const resetDynamicConfigStates = async () => {
  showDynamicProcessorDropdown.value = {};
  await initializeDynamicConfigs();
};

// 验证动态配置
const validateDynamicConfigs = () => {
  let isValid = true;
  
  dynamicFieldConfigs.value.forEach(configItem => {
    // 检查是否至少配置了一个完整的字段（字段名和字段值都不为空）
    const hasValidFieldConfig = configItem.fieldConfigs.some(config => 
      config.fieldName && config.fieldName.trim() && 
      config.fieldValue && config.fieldValue.trim()
    );
    if (!hasValidFieldConfig) {
      isValid = false;
    }
    
    // 检查是否选择了处理员工
    if (!configItem.processor) {
      isValid = false;
    }
  });
  
  return isValid;
};

// 获取动态配置数据
const getDynamicConfigData = () => {
  return dynamicFieldConfigs.value.map((configItem, index) => ({
    configIndex: index + 1,
    fieldConfigs: configItem.fieldConfigs.filter(config => 
      config.fieldName && config.fieldName.trim() && 
      config.fieldValue && config.fieldValue.trim()
    ),
    processorId: configItem.processor ? 
      (configItem.processor.id || configItem.processor.userId || configItem.processor.authId) : null,
    processorName: configItem.processor ? 
      (configItem.processor.userName || configItem.processor.cnName || configItem.processor.name) : null
  })).filter(item => item.fieldConfigs.length > 0 && item.processorId);
};

// 加载动态配置数据
const loadDynamicConfigData = async (configData) => {
  await resetDynamicConfigStates();
  
  if (configData && Array.isArray(configData) && configData.length > 0) {
    dynamicFieldConfigs.value = configData.map(item => {
      const configItem = {
        id: ++dynamicConfigIdCounter,
        fieldConfigs: [],
        processor: null,
        processorSearchKeyword: ''
      };
      
      // 处理字段配置数据
      if (Array.isArray(item.fieldConfigs)) {
        configItem.fieldConfigs = item.fieldConfigs.map(config => ({
          fieldName: config.fieldName || '',
          fieldValue: config.fieldValue || ''
        }));
      } else if (Array.isArray(item.fieldValues)) {
        // 兼容旧的fieldValues格式
        configItem.fieldConfigs = item.fieldValues.map(value => ({
          fieldName: '',
          fieldValue: value || ''
        }));
      } else {
        // 兼容更旧的格式
        const values = [item.field1Value || '', item.field2Value || ''].filter(v => v);
        configItem.fieldConfigs = values.map(value => ({
          fieldName: '',
          fieldValue: value
        }));
      }
      
      // 确保至少有一个字段配置
      if (configItem.fieldConfigs.length === 0) {
        configItem.fieldConfigs = [{ fieldName: '', fieldValue: '' }];
      }
      
      // 查找处理员工
      const processorId = item.processorId || item.processor1Id;
      if (processorId && currentRoleData.value?.departmentId) {
        const deptUsers = departmentUsers.value.get(currentRoleData.value.departmentId) || [];
        const processor = deptUsers.find(user => 
          (user.id || user.userId || user.authId) === processorId
        );
        if (processor) {
          configItem.processor = processor;
        }
      }
      
      return configItem;
    });
  } else {
    await initializeDynamicConfigs();
  }
};

// 获取过滤后的部门用户（用于管理模态框）
const getFilteredManageDepartmentUsers = () => {
  if (!currentRoleData.value?.departmentId) return [];
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(currentRoleData.value.departmentId) || [];
  const searchKeyword = manageOwnerSearchKeyword.value.toLowerCase().trim();
  
  if (!searchKeyword) {
    return deptUsers;
  }
  
  return deptUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase();
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase();
    
    return userName.includes(searchKeyword) || authId.includes(searchKeyword);
  });
};

// 选择管理模态框的负责人
const selectManageOwner = (user) => {
  selectedOwner.value = user;
  manageOwnerSearchKeyword.value = '';
  showManageOwnerDropdown.value = false;
  showManageOwnerError.value = false;
};

// 移除管理模态框的负责人
const removeManageOwner = () => {
  selectedOwner.value = null;
  manageOwnerSearchKeyword.value = '';
  showManageOwnerError.value = false;
};

// 字段值变更处理
const onFieldValueChange = (fieldKey, value) => {
  fieldValues.value[fieldKey] = value;
  // 清除该字段的错误状态
  if (fieldProcessorErrors.value[fieldKey]) {
    fieldProcessorErrors.value[fieldKey] = false;
  }
};

// 更新字段处理员工搜索关键词
const updateFieldProcessorSearch = (fieldKey, value) => {
  fieldProcessorSearchKeywords.value[fieldKey] = value;
};

// 隐藏字段处理员工下拉框
const hideFieldProcessorDropdown = (fieldKey) => {
  setTimeout(() => {
    showFieldProcessorDropdown.value[fieldKey] = false;
  }, 200);
};

// 获取过滤后的字段处理员工用户
const getFilteredFieldProcessorUsers = (fieldKey) => {
  if (!currentRoleData.value?.departmentId) return [];
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(currentRoleData.value.departmentId) || [];
  const searchKeyword = (fieldProcessorSearchKeywords.value[fieldKey] || '').toLowerCase().trim();
  
  if (!searchKeyword) {
    return deptUsers;
  }
  
  return deptUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase();
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase();
    
    return userName.includes(searchKeyword) || authId.includes(searchKeyword);
  });
};

// 选择字段处理员工
const selectFieldProcessor = (fieldKey, user) => {
  fieldProcessors.value[fieldKey] = user;
  fieldProcessorSearchKeywords.value[fieldKey] = '';
  showFieldProcessorDropdown.value[fieldKey] = false;
  fieldProcessorErrors.value[fieldKey] = false;
};

// 移除字段处理员工
const removeFieldProcessor = (fieldKey) => {
  fieldProcessors.value[fieldKey] = null;
  fieldProcessorSearchKeywords.value[fieldKey] = '';
  fieldProcessorErrors.value[fieldKey] = false;
};

// 重置字段配置状态
const resetFieldConfigStates = () => {
  fieldValues.value = {};
  fieldProcessors.value = {};
  fieldProcessorSearchKeywords.value = {};
  showFieldProcessorDropdown.value = {};
  fieldProcessorErrors.value = {};
};

// 验证字段配置
const validateFieldConfigs = () => {
  let isValid = true;
  
  roleFieldConfigs.value.forEach((config, index) => {
    const fieldKey = config.code || index;
    
    // 检查是否有字段值但没有处理员工
    if (fieldValues.value[fieldKey] && !fieldProcessors.value[fieldKey]) {
      fieldProcessorErrors.value[fieldKey] = true;
      isValid = false;
    }
    
    // 检查是否有处理员工但没有字段值
    if (fieldProcessors.value[fieldKey] && !fieldValues.value[fieldKey]) {
      // 可以选择是否强制要求字段值，这里暂时不强制
      // fieldProcessorErrors.value[fieldKey] = true;
      // isValid = false;
    }
  });
  
  return isValid;
};

// 获取字段配置数据
const getFieldConfigData = () => {
  const fieldConfigData = [];
  
  roleFieldConfigs.value.forEach((config, index) => {
    const fieldKey = config.code || index;
    
    if (fieldValues.value[fieldKey] || fieldProcessors.value[fieldKey]) {
      fieldConfigData.push({
        fieldName: config.name || '未命名字段',
        fieldCode: config.code || `field_${index}`,
        fieldValue: fieldValues.value[fieldKey] || '',
        processorId: fieldProcessors.value[fieldKey] ? 
          (fieldProcessors.value[fieldKey].id || fieldProcessors.value[fieldKey].userId || fieldProcessors.value[fieldKey].authId) : null,
        processorName: fieldProcessors.value[fieldKey] ? 
          (fieldProcessors.value[fieldKey].userName || fieldProcessors.value[fieldKey].cnName || fieldProcessors.value[fieldKey].name) : null,
        processorAuthId: fieldProcessors.value[fieldKey] ? 
          (fieldProcessors.value[fieldKey].authId || fieldProcessors.value[fieldKey].id || fieldProcessors.value[fieldKey].userId) : null
      });
    }
  });
  
  return fieldConfigData;
};

// 加载字段配置数据
const loadFieldConfigData = (configData) => {
  resetFieldConfigStates();
  
  if (configData && Array.isArray(configData)) {
    configData.forEach(item => {
      const fieldKey = item.fieldCode || item.fieldName;
      
      if (fieldKey) {
        fieldValues.value[fieldKey] = item.fieldValue || '';
        
        if (item.processorId) {
          // 从部门用户中查找对应的处理员工
          const deptUsers = departmentUsers.value.get(currentRoleData.value?.departmentId) || [];
          const processor = deptUsers.find(user => 
            (user.id || user.userId || user.authId) === item.processorId
          );
          
          if (processor) {
            fieldProcessors.value[fieldKey] = processor;
          }
        }
      }
    });
  }
};

// 关闭模态框
const closeModal = () => {
  showModal.value = false;
  isEditMode.value = false;
  currentRuleId.value = null;
  selectedOwner.value = null;
  ownerSearchKeyword.value = '';
  showOwnerDropdownOld.value = false;
};

// 关闭默认负责人配置模态框
const closeOwnerConfigModal = () => {
  ownerConfigModalVisible.value = false;
  ownerConfigFormData.value = {
    roleId: '',
    departmentRows: []
  };
  ownerConfigDepartmentRows.value = [];
  activeOwnerConfigDepartmentIndex.value = null;
  ownerConfigDepartmentSearchKeywords.value.clear();
};

// 关闭管理模态框
const closeManageModal = () => {
  manageModalVisible.value = false;
  currentRoleData.value = null;
  roleFieldConfigs.value = [];
  selectedOwner.value = null;
  
  // 重置搜索状态
  manageOwnerSearchKeyword.value = '';
  showManageOwnerDropdown.value = false;
  showManageOwnerError.value = false;
  
  // 重置字段配置状态
  resetFieldConfigStates();
  
  // 重置动态配置状态
  resetDynamicConfigStates();
};

// 保存路由规则
const saveRoutingRule = async () => {
  if (!formData.value.roleId || !formData.value.departmentId) {
    showBasicInfoError.value = true;
    return;
  }
  
  if (!selectedOwner.value) {
    showOwnerError.value = true;
    return;
  }
  
  try {
    const routeData = {
      roleId: formData.value.roleId,
      departmentId: formData.value.departmentId,
      userId: selectedOwner.value.id || selectedOwner.value.userId,
      routeFields: formData.value.routeFields || []
    };
    
    if (isEditMode.value) {
      await updateRoleDepartmentUser(currentRuleId.value, routeData);
    } else {
      await createRoleDepartmentUser(routeData);
    }
    
    await fetchRoleDepartmentUsers();
    closeModal();
  } catch (error) {
    console.error('保存路由规则失败:', error);
  }
};

// 保存默认负责人配置
const saveOwnerConfig = async () => {
  if (!ownerConfigFormData.value.roleId) {
    ownerConfigShowBasicInfoError.value = true;
    return;
  }
  
  if (ownerConfigDepartmentRows.value.length === 0 || !allOwnerConfigDepartmentsHaveOwners()) {
    ownerConfigShowOwnerError.value = true;
    return;
  }
  
  try {
    const promises = [];
    
    // 为每个部门的每个用户创建一条记录
    ownerConfigDepartmentRows.value.forEach(row => {
      row.owners.forEach(owner => {
        // 获取角色信息
        const selectedRole = roles.value.find(role => 
          (role.id || role.roleId) === ownerConfigFormData.value.roleId
        );
        
        // 获取部门信息
        const selectedDepartment = departments.value.find(dept => 
          dept.deptId === row.departmentId
        );
        
        // 构造符合后端要求的请求体格式
        const routeData = {
          roleConfigId: ownerConfigFormData.value.roleId,  // 角色配置ID（必填）
          departmentId: row.departmentId,                  // 部门ID（必填）
          userId: owner.id || owner.userId || owner.authId, // 用户ID（必填）
          isDefault: true,                                 // 是否默认
          
          // 冗余字段（可选，如果不提供将通过业务逻辑自动填充）
          roleName: selectedRole ? selectedRole.roleName : null,
          departmentName: selectedDepartment ? selectedDepartment.deptName : null,
          userName: owner.userName || owner.cnName || owner.name || null,
          userAuthid: owner.authId || owner.id || owner.userId || null
        };
        
        promises.push(createRoleDepartmentUser(routeData));
      });
    });
    
    await Promise.all(promises);
    await fetchRoleDepartmentUsers();
    closeOwnerConfigModal();
  } catch (error) {
    console.error('保存默认负责人配置失败:', error);
  }
};

// 保存管理配置
const saveManageConfig = async () => {
  // 验证负责人是否已选择
  if (!selectedOwner.value) {
    showManageOwnerError.value = true;
    message.error('请选择负责人');
    return;
  }
  
  // 验证字段配置
  if (!validateFieldConfigs()) {
    message.error('请为有字段值的字段选择处理员工');
    return;
  }
  
  // 验证动态配置
  if (!validateDynamicConfigs()) {
    message.error('请为动态配置选择处理人');
    return;
  }
  
  if (!currentRoleData.value) {
    message.error('缺少角色数据');
    return;
  }
  
  try {
    // 获取角色信息
    const selectedRole = roles.value.find(role => 
      (role.id || role.roleId) === (currentRoleData.value.roleId || currentRoleData.value.roleConfigId)
    );
    
    // 获取部门信息
    const selectedDepartment = departments.value.find(dept => 
      dept.deptId === currentRoleData.value.departmentId
    );
    
    // 获取字段配置数据
    const fieldConfigData = getFieldConfigData();
    
    // 获取动态配置数据
    const dynamicConfigData = getDynamicConfigData();
    
    // 构造符合后端要求的请求体格式
    const updateData = {
      roleConfigId: currentRoleData.value.roleId || currentRoleData.value.roleConfigId, // 角色配置ID（必填）
      departmentId: currentRoleData.value.departmentId,                                 // 部门ID（必填）
      userId: selectedOwner.value.id || selectedOwner.value.userId || selectedOwner.value.authId, // 用户ID（必填）
      isDefault: currentRoleData.value.isDefault || false,                             // 是否默认
      fieldConfigData: fieldConfigData,                                                // 字段配置数据
      dynamicConfigData: dynamicConfigData,                                            // 动态配置数据
      
      // 冗余字段（可选，如果不提供将通过业务逻辑自动填充）
      roleName: selectedRole ? selectedRole.roleName : null,
      departmentName: selectedDepartment ? selectedDepartment.deptName : null,
      userName: selectedOwner.value.userName || selectedOwner.value.cnName || selectedOwner.value.name || null,
      userAuthid: selectedOwner.value.authId || selectedOwner.value.id || selectedOwner.value.userId || null
    };
    
    if (currentRoleData.value.id) {
      await deleteRoleDepartmentUser(currentRoleData.value.id);
    }
    
    await createRoleDepartmentUser(updateData);
    message.success('管理配置保存成功');
    closeManageModal();
    fetchAllData();
  } catch (error) {
    console.error('保存配置失败:', error);
    message.error('保存管理配置失败');
  }
};

// 验证提交数据
const validateSubmitData = () => {
  if (!currentRoleData.value || !selectedOwner.value) {
    return false;
  }
  
  // 检查是否有动态配置中的字段值
  const hasDynamicConfig = dynamicFieldConfigs.value.some(config => {
    return config.fieldConfigs && config.fieldConfigs.length > 0 && 
           config.fieldConfigs.some(fieldConfig => 
             fieldConfig.fieldName && fieldConfig.fieldValue && fieldConfig.fieldValue.trim()
           );
  });
  
  return hasDynamicConfig;
};

// 提交路由规则
const submitRoutingRule = async () => {
  if (!validateSubmitData()) {
    message.error('请在动态配置中至少配置一个字段值后再提交');
    return;
  }
  
  try {
    // 调试信息：打印字段配置状态
    console.log('=== 字段配置调试信息 ===');
    console.log('roleFieldConfigs:', roleFieldConfigs.value);
    console.log('fieldValues:', fieldValues.value);
    console.log('dynamicFieldConfigs:', dynamicFieldConfigs.value);
    console.log('========================');
    
    // 构造字段值数据 - 只从动态配置中获取
    const fieldValuesData = {};
    
    // 从动态配置中获取字段值
    dynamicFieldConfigs.value.forEach((config, configIndex) => {
      if (config.fieldConfigs && config.fieldConfigs.length > 0) {
        config.fieldConfigs.forEach((fieldConfig, fieldIndex) => {
          if (fieldConfig.fieldName && fieldConfig.fieldValue) {
            // 使用字段名称作为key，而不是动态key
            fieldValuesData[fieldConfig.fieldName] = fieldConfig.fieldValue;
          }
        });
      }
    });
    
    // 构造分配用户数据
    const assignedUsersData = {
      primaryUser: {
        id: selectedOwner.value.id || selectedOwner.value.userId || selectedOwner.value.authId,
        name: selectedOwner.value.userName || selectedOwner.value.cnName || selectedOwner.value.name,
        authId: selectedOwner.value.authId || selectedOwner.value.id || selectedOwner.value.userId
      }
    };
    
    // 添加字段处理人
    const fieldProcessorsData = {};
    roleFieldConfigs.value.forEach(field => {
      const processor = fieldProcessors.value[field.code];
      if (processor) {
        fieldProcessorsData[field.code] = {
          id: processor.id || processor.userId || processor.authId,
          name: processor.userName || processor.cnName || processor.name,
          authId: processor.authId || processor.id || processor.userId
        };
      }
    });
    
    if (Object.keys(fieldProcessorsData).length > 0) {
      assignedUsersData.fieldProcessors = fieldProcessorsData;
    }
    
    // 添加动态配置处理人
    const dynamicProcessorsData = {};
    dynamicFieldConfigs.value.forEach((config, configIndex) => {
      if (config.processors && config.processors.length > 0) {
        dynamicProcessorsData[`config_${configIndex}`] = config.processors.map(processor => ({
          id: processor.id || processor.userId || processor.authId,
          name: processor.userName || processor.cnName || processor.name,
          authId: processor.authId || processor.id || processor.userId
        }));
      }
    });
    
    if (Object.keys(dynamicProcessorsData).length > 0) {
      assignedUsersData.dynamicProcessors = dynamicProcessorsData;
    }
    
    // 构造请求数据
    const requestData = {
      roleConfigId: currentRoleData.value.roleId || currentRoleData.value.roleConfigId,
      roleName: currentRoleData.value.roleName,
      deptId: currentRoleData.value.departmentId || currentRoleData.value.deptId,
      deptName: currentRoleData.value.departmentName || currentRoleData.value.deptName,
      fieldValues: JSON.stringify(fieldValuesData),
      assignedUsers: JSON.stringify(assignedUsersData)
    };
    
    console.log('提交路由规则数据:', requestData);
    
    // 调用API提交路由规则
    const response = await createRoutingRule(requestData);
    
    console.log('路由规则提交成功:', response);
    message.success('路由规则提交成功');
    
    // 关闭模态框并刷新数据
    closeManageModal();
    fetchAllData();
    
  } catch (error) {
    console.error('提交路由规则失败:', error);
    message.error('提交路由规则失败: ' + (error.message || '未知错误'));
  }
};

// 处理删除操作
const handleDelete = async (row) => {
  if (confirm('确定要删除这条路由规则吗？')) {
    try {
      await deleteRoleDepartmentUser(row.id);
      await fetchRoleDepartmentUsers();
    } catch (error) {
      console.error('删除路由规则失败:', error);
    }
  }
};

// 选择负责人
const selectOwner = (user) => {
  selectedOwner.value = user;
  ownerSearchKeyword.value = user.userName;
  showOwnerDropdownOld.value = false;
  showOwnerError.value = false;
};

// 移除负责人
const removeOwner = () => {
  selectedOwner.value = null;
  ownerSearchKeyword.value = '';
};

// 处理角色变更
const onRoleChange = () => {
  showBasicInfoError.value = false;
  showOwnerError.value = false;
};

// 处理部门变更
const onDepartmentChange = () => {
  showBasicInfoError.value = false;
  showOwnerError.value = false;
};

// 处理默认负责人配置模态框中的角色变更
const onOwnerConfigRoleChange = async () => {
  ownerConfigDepartmentRows.value = [];
  ownerConfigShowBasicInfoError.value = false;
  ownerConfigShowOwnerError.value = false;
  selectedRoleDepartments.value = [];
  
  if (departments.value.length === 0) {
    await fetchDepartments();
  }
  
  // 如果选择了角色，解析角色的部门配置
  if (ownerConfigFormData.value.roleId) {
    try {
      const roleConfig = await getRoleConfigById(ownerConfigFormData.value.roleId);
      console.log('获取到的角色配置:', roleConfig);
      console.log('角色配置数据结构:', roleConfig.data);
      if (roleConfig && roleConfig.data && roleConfig.data.departmentAssignments) {
        // 解析departmentAssignments JSON字符串
        const departmentAssignments = JSON.parse(roleConfig.data.departmentAssignments);
        console.log('解析后的部门配置:', departmentAssignments);
        if (departmentAssignments && departmentAssignments.departments) {
          selectedRoleDepartments.value = departmentAssignments.departments;
          console.log('设置的角色部门:', selectedRoleDepartments.value);
        }
      } else {
        console.log('角色配置中没有找到departmentAssignments字段');
      }
    } catch (error) {
      console.error('解析角色部门配置失败:', error);
      selectedRoleDepartments.value = [];
    }
  }
};

// 添加部门行
const addDepartmentRow = () => {
  const newIndex = ownerConfigDepartmentRows.value.length;
  ownerConfigDepartmentRows.value.push({
    departmentId: '',
    owners: [] // 改为数组支持多个用户
  });
  
  // 初始化负责人搜索关键词和下拉框状态
  setOwnerSearchKeyword(newIndex, '');
  ownerDropdownVisible.value.set(newIndex, false);
  
  // 初始化部门搜索关键词和下拉框状态
  setDepartmentSearchKeyword(newIndex, '');
  departmentDropdownVisible.value.set(newIndex, false);
};

// 移除部门行
const removeDepartmentRow = (index) => {
  ownerConfigDepartmentRows.value.splice(index, 1);
  
  // 清理负责人搜索状态
  ownerSearchKeywords.value.delete(index);
  ownerDropdownVisible.value.delete(index);
  
  // 清理部门搜索状态
  departmentSearchKeywords.value.delete(index);
  departmentDropdownVisible.value.delete(index);
  
  // 重新索引剩余的负责人搜索状态
  const newOwnerKeywords = new Map();
  const newOwnerDropdownVisible = new Map();
  
  // 重新索引剩余的部门搜索状态
  const newDepartmentKeywords = new Map();
  const newDepartmentDropdownVisible = new Map();
  
  ownerConfigDepartmentRows.value.forEach((_, newIndex) => {
    const oldIndex = newIndex >= index ? newIndex + 1 : newIndex;
    
    // 重新索引负责人搜索状态
    if (ownerSearchKeywords.value.has(oldIndex)) {
      newOwnerKeywords.set(newIndex, ownerSearchKeywords.value.get(oldIndex));
    }
    if (ownerDropdownVisible.value.has(oldIndex)) {
      newOwnerDropdownVisible.set(newIndex, ownerDropdownVisible.value.get(oldIndex));
    }
    
    // 重新索引部门搜索状态
    if (departmentSearchKeywords.value.has(oldIndex)) {
      newDepartmentKeywords.set(newIndex, departmentSearchKeywords.value.get(oldIndex));
    }
    if (departmentDropdownVisible.value.has(oldIndex)) {
      newDepartmentDropdownVisible.set(newIndex, departmentDropdownVisible.value.get(oldIndex));
    }
  });
  
  ownerSearchKeywords.value = newOwnerKeywords;
  ownerDropdownVisible.value = newOwnerDropdownVisible;
  departmentSearchKeywords.value = newDepartmentKeywords;
  departmentDropdownVisible.value = newDepartmentDropdownVisible;
};

// 处理部门变更
const onOwnerConfigDepartmentChange = async (index) => {
  const row = ownerConfigDepartmentRows.value[index];
  // 清空已选择的用户，因为部门变更了
  row.owners = [];
  
  // 清空负责人搜索关键词和隐藏下拉框
  setOwnerSearchKeyword(index, '');
  ownerDropdownVisible.value.set(index, false);
  
  // 清空部门搜索关键词和隐藏下拉框
  setDepartmentSearchKeyword(index, '');
  departmentDropdownVisible.value.set(index, false);
  
  // 如果选择了部门，获取该部门的用户
  if (row.departmentId) {
    try {
      console.log('获取部门用户，部门ID:', row.departmentId);
      const response = await userService.getUsersByDepartment(row.departmentId);
      console.log('获取到的部门用户响应:', response);
      
      // 处理响应数据，确保数据结构正确
      let userData = [];
      if (response && response.data) {
        userData = Array.isArray(response.data) ? response.data : [response.data];
      } else if (response && Array.isArray(response)) {
        userData = response;
      }
      
      console.log('处理后的用户数据:', userData);
      
      // 将用户数据存储到departmentUsers中
      departmentUsers.value.set(row.departmentId, userData);
      
      // 如果没有获取到用户数据，尝试使用全局用户数据作为备选
      if (userData.length === 0) {
        console.log('部门用户为空，使用全局用户数据作为备选');
        departmentUsers.value.set(row.departmentId, users.value || []);
      }
    } catch (error) {
      console.error('获取部门用户失败:', error);
      // 如果获取失败，使用全局用户数据作为备选
      console.log('获取失败，使用全局用户数据作为备选');
      departmentUsers.value.set(row.departmentId, users.value || []);
    }
  }
};

// 获取可用用户列表（排除已选择的用户）
const getAvailableUsersForDepartment = (departmentId, index) => {
  if (!departmentId) {
    return [];
  }
  
  // 从departmentUsers中获取该部门的用户数据
  const deptUsers = departmentUsers.value.get(departmentId) || [];
  console.log('部门用户数据:', deptUsers);
  
  const row = ownerConfigDepartmentRows.value[index];
  if (!row || !row.owners) {
    console.log('返回所有部门用户，因为没有已选择的用户');
    return deptUsers;
  }
  
  // 获取已选择用户的ID列表，兼容不同的ID字段
  const selectedOwnerIds = row.owners.map(owner => owner.id || owner.userId || owner.authId).filter(Boolean);
  console.log('已选择的用户ID:', selectedOwnerIds);
  
  // 过滤掉已选择的用户，兼容不同的ID字段
  const availableUsers = deptUsers.filter(user => {
    const userId = user.id || user.userId || user.authId;
    return !selectedOwnerIds.includes(userId);
  });
  
  console.log('可用用户列表:', availableUsers);
  return availableUsers;
};

// 获取搜索关键词
const getOwnerSearchKeyword = (index) => {
  return ownerSearchKeywords.value.get(index) || '';
};

// 设置搜索关键词
const setOwnerSearchKeyword = (index, keyword) => {
  ownerSearchKeywords.value.set(index, keyword);
};

// 显示下拉框
const showOwnerDropdown = (index) => {
  ownerDropdownVisible.value.set(index, true);
};

// 隐藏下拉框
const hideOwnerDropdown = (index) => {
  setTimeout(() => {
    ownerDropdownVisible.value.set(index, false);
  }, 200); // 延迟隐藏，允许点击选项
};

// 检查下拉框是否可见
const isOwnerDropdownVisible = (index) => {
  return ownerDropdownVisible.value.get(index) || false;
};

// 获取过滤后的可用用户列表
const getFilteredAvailableUsers = (departmentId, index) => {
  const availableUsers = getAvailableUsersForDepartment(departmentId, index);
  const searchKeyword = getOwnerSearchKeyword(index).toLowerCase().trim();
  
  if (!searchKeyword) {
    return availableUsers;
  }
  
  return availableUsers.filter(user => {
    const userName = (user.userName || user.cnName || user.name || '').toLowerCase();
    const authId = (user.authId || user.id || user.userId || '').toString().toLowerCase();
    
    return userName.includes(searchKeyword) || authId.includes(searchKeyword);
  });
};

// 从搜索结果中选择用户
const selectOwnerFromSearch = (index, user) => {
  const row = ownerConfigDepartmentRows.value[index];
  
  if (!row.owners) {
    row.owners = [];
  }
  
  // 检查用户是否已经被选择
  const userId = user.id || user.userId || user.authId;
  const isAlreadySelected = row.owners.some(owner => {
    const ownerId = owner.id || owner.userId || owner.authId;
    return ownerId === userId;
  });
  
  if (!isAlreadySelected) {
    row.owners.push(user);
    console.log('已选择的负责人列表:', row.owners);
  }
  
  // 清空搜索关键词并隐藏下拉框
  setOwnerSearchKeyword(index, '');
  ownerDropdownVisible.value.set(index, false);
};

// 部门搜索相关函数
// 获取部门搜索关键词
const getDepartmentSearchKeyword = (index) => {
  return departmentSearchKeywords.value.get(index) || '';
};

// 设置部门搜索关键词
const setDepartmentSearchKeyword = (index, keyword) => {
  departmentSearchKeywords.value.set(index, keyword);
};

// 显示部门下拉框
const showDepartmentDropdown = (index) => {
  departmentDropdownVisible.value.set(index, true);
};

// 隐藏部门下拉框
const hideDepartmentDropdown = (index) => {
  setTimeout(() => {
    departmentDropdownVisible.value.set(index, false);
  }, 200); // 延迟隐藏，允许点击选项
};

// 检查部门下拉框是否可见
const isDepartmentDropdownVisible = (index) => {
  return departmentDropdownVisible.value.get(index) || false;
};

// 获取过滤后的可用部门列表
const getFilteredAvailableDepartments = (index) => {
  const searchKeyword = getDepartmentSearchKeyword(index).toLowerCase().trim();
  
  if (!searchKeyword) {
    return filteredDepartmentsForRole.value;
  }
  
  return filteredDepartmentsForRole.value.filter(dept => {
    const deptName = (dept.deptName || '').toLowerCase();
    
    return deptName.includes(searchKeyword);
  });
};

// 从搜索结果中选择部门
const selectDepartmentFromSearch = (index, department) => {
  const row = ownerConfigDepartmentRows.value[index];
  row.departmentId = department.deptId;
  
  // 清空搜索关键词并隐藏下拉框
  setDepartmentSearchKeyword(index, '');
  departmentDropdownVisible.value.set(index, false);
  
  // 触发部门变更处理
  onOwnerConfigDepartmentChange(index);
};

// 获取部门显示名称
const getDepartmentDisplayName = (index) => {
  const row = ownerConfigDepartmentRows.value[index];
  if (!row || !row.departmentId) {
    return '';
  }
  
  const department = departments.value.find(dept => dept.deptId === row.departmentId);
  return department ? department.deptName : '';
};

// 从下拉框选择负责人（保留原有函数以兼容）
const selectOwnerFromDropdown = (index, event) => {
  const userId = event.target.value;
  console.log('选择的用户ID:', userId);
  
  if (!userId) {
    return;
  }
  
  const row = ownerConfigDepartmentRows.value[index];
  const deptUsers = departmentUsers.value.get(row.departmentId) || [];
  console.log('部门用户数据:', deptUsers);
  
  // 兼容不同的ID字段查找用户
  const selectedUser = deptUsers.find(user => {
    const userIdValue = user.id || user.userId || user.authId;
    return userIdValue && userIdValue.toString() === userId.toString();
  });
  
  console.log('找到的用户:', selectedUser);
  
  if (selectedUser) {
    // 确保owners数组存在
    if (!row.owners) {
      row.owners = [];
    }
    
    // 添加用户到已选列表
    row.owners.push(selectedUser);
    console.log('已选择的负责人列表:', row.owners);
    
    // 重置下拉框选择
    event.target.value = '';
  } else {
    console.error('未找到对应的用户');
  }
};

// 移除单个负责人
const removeOwnerConfigOwner = (index, userIndex) => {
  ownerConfigDepartmentRows.value[index].owners.splice(userIndex, 1);
};

// 移除所有负责人
const removeAllOwnerConfigOwners = (index) => {
  ownerConfigDepartmentRows.value[index].owners = [];
};

// 检查是否所有部门都有负责人
const allOwnerConfigDepartmentsHaveOwners = () => {
  return ownerConfigDepartmentRows.value.every(row => row.departmentId && row.owners && row.owners.length > 0);
};

// 处理字段选择
const handleFieldSelection = (fieldId, isSelected) => {
  if (isSelected) {
    selectedFieldIds.value.push(fieldId);
  } else {
    selectedFieldIds.value = selectedFieldIds.value.filter(id => id !== fieldId);
  }
};

// 移除已选择的字段
const removeSelectedField = (fieldId) => {
  selectedFieldIds.value = selectedFieldIds.value.filter(id => id !== fieldId);
};

// 拖放相关函数
const handleDragStart = (fieldId) => {
  draggedFieldId.value = fieldId;
};

const handleDragOver = (e) => {
  e.preventDefault();
};

const handleDrop = (targetFieldId) => {
  if (draggedFieldId.value === targetFieldId || draggedFieldId.value === 'dept') {
    return;
  }
  
  const draggedIndex = selectedFieldIds.value.indexOf(draggedFieldId.value);
  const targetIndex = selectedFieldIds.value.indexOf(targetFieldId);
  
  if (draggedIndex !== -1 && targetIndex !== -1) {
    const newFieldIds = [...selectedFieldIds.value];
    const [removed] = newFieldIds.splice(draggedIndex, 1);
    newFieldIds.splice(targetIndex, 0, removed);
    selectedFieldIds.value = newFieldIds;
  }
  
  draggedFieldId.value = null;
};

// 进入下一步
const goToNextStep = () => {
  if (!formData.value.roleId || selectedDepartments.value.length === 0) {
    showBasicInfoError.value = true;
    showOwnerError.value = false;
    return;
  }
  
  if (!allDepartmentsHaveOwners()) {
    showOwnerError.value = true;
    showBasicInfoError.value = false;
    return;
  }
  
  step1RouteFields.value = selectedRouteFields.value;
  showBasicInfoError.value = false;
  showOwnerError.value = false;
  currentStep.value = 2;
};

// 返回上一步
const goToPrevStep = () => {
  currentStep.value = 1;
  showStep2Error.value = false;
  showStep2OwnerError.value = false;
};

// 跳转到指定步骤
const goToStep = (step) => {
  if (step === 1) {
    currentStep.value = 1;
  } else if (step === 2 && currentStep.value > 1) {
    currentStep.value = 2;
  }
};

// 检查是否已为所有部门选择负责人
const allDepartmentsHaveOwners = () => {
  return selectedDepartments.value.every(dept => departmentOwners.value.has(dept.id));
};

// 获取用户名首字母用于头像显示
const getUserInitial = (userName) => {
  if (!userName || userName === '未设置') {
    return '?';
  }
  return userName.charAt(0).toUpperCase();
};

// 组件挂载时获取所有数据
onMounted(() => {
  fetchAllData();
});

// 组件卸载时的清理工作
onUnmounted(() => {
  // 清理工作（如果需要）
});

// 处理分页变化
const handleCurrentChange = (newPage) => {
  if (newPage >= 1 && newPage <= totalPages.value) {
    currentPage.value = newPage;
  }
};

// 处理每页条数变化
const handleSizeChange = () => {
  currentPage.value = 1;
};
</script>

<style scoped>
/* 基础页面样式 - 与RoleRouteManagement保持一致 */
.routing-rules-management {
  width: 100%;
  padding: var(--spacing-xl);
}

.page-header {
  margin-bottom: var(--spacing-xl);
  display: flex;
  align-items: center;
  gap: var(--spacing-md);
}

.page-header h2 {
  font-size: var(--font-size-xl);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

/* 卡片样式继承 */
.card {
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-base);
  overflow: hidden;
  transition: box-shadow 0.3s ease;
}

.card:hover {
  box-shadow: var(--shadow-md);
}

/* 工具栏样式继承 */
.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  flex-wrap: wrap;
  gap: var(--spacing-lg);
}

/* 搜索容器样式继承 */
.search-container {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
  flex: 1;
  min-width: 280px;
}

/* 规则容器样式 */
.rules-container {
  padding: var(--spacing-lg);
}

.rules-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: var(--spacing-lg);
}

/* 规则卡片样式 */
.rule-card {
  background: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-lg);
  padding: var(--spacing-lg);
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.rule-card:hover {
  box-shadow: var(--shadow-md);
  transform: translateY(-2px);
}

/* 规则头部 */
.rule-header {
  margin-bottom: var(--spacing-lg);
  padding-bottom: var(--spacing-md);
  border-bottom: 2px solid var(--primary-color);
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.rule-title-section {
  flex: 1;
}

.role-name {
  margin: 0 0 var(--spacing-xs) 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--primary-color);
  display: flex;
  align-items: center;
  gap: 8px;
}

.department-suffix {
  font-size: 14px;
  color: var(--text-secondary);
  font-weight: 500;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  padding: 4px 8px;
  border-radius: 6px;
  border: 1px solid #bae6fd;
  transition: all 0.3s ease;
}

.department-suffix:hover {
  background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  border-color: #0ea5e9;
  color: var(--primary-color);
}

/* 操作按钮容器 */
.action-buttons {
  display: flex;
  gap: var(--spacing-xs);
}

/* 编辑、管理和删除按钮 */
.edit-btn,
.manage-btn,
.delete-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: var(--spacing-xs);
  border-radius: var(--border-radius-md);
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
}

.edit-btn:hover {
  background-color: #e3f2fd;
  transform: scale(1.1);
}

.manage-btn:hover {
  background-color: #f3e5f5;
  transform: scale(1.1);
}

.delete-btn:hover {
  background-color: #fee;
  transform: scale(1.1);
}

.edit-icon {
  font-size: 16px;
  color: #2196f3;
}

.manage-icon {
  font-size: 16px;
  color: #9c27b0;
}

.delete-icon {
  font-size: 16px;
  color: #e74c3c;
}

/* 用户信息部分 */
.user-info-section {
  margin-bottom: var(--spacing-lg);
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-sm);
}

.user-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm);
  background: var(--bg-light);
  border-radius: var(--border-radius-md);
  border-left: 3px solid var(--primary-color);
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: linear-gradient(135deg, var(--primary-color) 0%, #1976d2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  margin-right: var(--spacing-md);
  flex-shrink: 0;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 2px;
}

.user-auth-id {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  margin-left: 4px;
  font-style: italic;
}

/* 统计信息部分 */
.stats-section {
  display: flex;
  gap: var(--spacing-lg);
  padding-top: var(--spacing-md);
  border-top: 1px solid var(--border-light);
}

.stat-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
  flex: 1;
}

.stat-label {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-weight: 500;
}

.stat-value {
  font-size: var(--font-size-base);
  color: var(--text-primary);
  font-weight: 600;
}

/* 部分标题样式 */
.section-title {
  font-size: var(--font-size-sm);
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 var(--spacing-sm) 0;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-lg);
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: var(--spacing-md);
}

.empty-text {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
}

/* 加载指示器 */
.loading-indicator {
  text-align: center;
  padding: var(--spacing-xl) var(--spacing-lg);
  color: var(--text-secondary);
}

.loading-icon {
  font-size: 48px;
  margin-bottom: var(--spacing-md);
  animation: spin 2s linear infinite;
}

.loading-text {
  font-size: var(--font-size-lg);
  color: var(--text-secondary);
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 分页容器 */
.pagination-container {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-base);
}

.pagination {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: var(--spacing-md);
}

.page-info {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
  margin-left: var(--spacing-lg);
}

.page-size-selector span {
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

/* 按钮样式 - 与RoleRouteManagement保持一致 */
.btn {
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-size: var(--font-size-sm);
  font-weight: 500;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
  text-decoration: none;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.btn-default {
  background-color: var(--bg-white);
  color: var(--text-primary);
  border: 1px solid var(--border-base);
}

.btn-default:hover:not(:disabled) {
  background-color: var(--bg-hover);
  border-color: var(--primary-color);
}

.btn-primary {
  background-color: var(--primary-color);
  color: white;
}

.btn-primary:hover:not(:disabled) {
  background-color: var(--primary-hover);
}

.btn-danger {
  background-color: var(--danger-color);
  color: white;
}

.btn-danger:hover:not(:disabled) {
  background-color: var(--danger-hover);
}

.button--submit {
  background-color: var(--primary-color);
  color: white;
  padding: var(--spacing-sm) var(--spacing-md);
  border: none;
  border-radius: var(--border-radius-md);
  cursor: pointer;
  font-size: var(--font-size-sm);
  font-weight: 500;
  transition: all 0.3s ease;
}

.button--submit:hover {
  background-color: var(--primary-hover);
}

/* 输入框样式 */
.input {
  padding: var(--spacing-sm);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-sm);
  transition: border-color 0.3s ease;
  width: 100%;
}

.input:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.1);
}

.input-group {
  display: flex;
  gap: var(--spacing-sm);
  align-items: center;
}

.select {
  padding: var(--spacing-sm);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-sm);
  background-color: var(--bg-white);
  cursor: pointer;
}

.select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 表格样式 */
.table {
  width: 100%;
  border-collapse: collapse;
  font-size: var(--font-size-sm);
}

.table th,
.table td {
  padding: var(--spacing-md);
  text-align: left;
  border-bottom: 1px solid var(--border-base);
}

.table th {
  background-color: var(--bg-light);
  font-weight: 600;
  color: var(--text-primary);
}

.table tr:hover {
  background-color: var(--bg-hover);
}

/* 消息提示样式 - 与RoleRouteManagement保持一致 */
.message {
  position: fixed;
  top: 20px;
  right: 20px;
  padding: var(--spacing-md);
  border-radius: var(--border-radius-md);
  box-shadow: var(--shadow-md);
  z-index: 1001;
  animation: slideInRight 0.3s ease;
  max-width: 400px;
  font-size: var(--font-size-sm);
  font-weight: 500;
}

.message-success {
  background-color: var(--success-color);
  color: white;
}

.message-error {
  background-color: var(--danger-color);
  color: white;
}

.message-warning {
  background-color: var(--warning-color);
  color: white;
}

.message-info {
  background-color: var(--info-color);
  color: white;
}

@keyframes slideInRight {
  from {
    opacity: 0;
    transform: translateX(100%);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 使用全局统一样式，仅保留特定于当前组件的样式 */
/* 模态框样式 - 与RoleRouteManagement保持一致 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.modal-content {
  width: 80%;
  max-width: 900px;
  max-height: 80vh;
  overflow-y: auto;
  background-color: var(--bg-white);
  border-radius: var(--border-radius-lg);
  box-shadow: var(--shadow-lg);
  animation: modalSlideIn 0.3s ease-out;
}

.large-modal {
  width: 90%;
  max-width: 1200px;
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  padding: var(--spacing-lg);
  border-bottom: 1px solid var(--border-base);
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: var(--font-size-lg);
  font-weight: 600;
  color: var(--text-primary);
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: var(--text-secondary);
  padding: 0;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: var(--border-radius-md);
  transition: all 0.3s ease;
}

.modal-close:hover {
  background-color: var(--bg-hover);
  color: var(--text-primary);
}

.modal-body {
  padding: var(--spacing-lg);
}

.modal-footer {
  padding: var(--spacing-lg);
  border-top: 1px solid var(--border-base);
  display: flex;
  justify-content: flex-end;
  gap: var(--spacing-md);
}

/* 表单样式 - 与RoleRouteManagement保持一致 */
.form-section {
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-lg);
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  border: 1px solid var(--border-base);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: var(--shadow-sm);
}

.section-title {
  font-size: var(--font-size-lg);
  margin-top: 0;
  margin-bottom: var(--spacing-md);
  color: var(--text-primary);
  font-weight: 600;
  padding-bottom: var(--spacing-sm);
  border-bottom: 2px solid var(--primary-color);
}

.form-group {
  margin-bottom: var(--spacing-md);
}

.form-group:last-child {
  margin-bottom: 0;
}

.form-label {
  display: block;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
  font-size: var(--font-size-sm);
}

.form-control {
  width: 100%;
  padding: var(--spacing-sm);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-sm);
  transition: border-color 0.3s ease;
}

.form-control:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(64, 169, 255, 0.1);
}

.form-control:disabled {
  background-color: var(--bg-light);
  color: var(--text-secondary);
  cursor: not-allowed;
}

.form-text {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  margin-top: var(--spacing-xs);
}

.form-error {
  color: var(--danger-color);
  font-size: var(--font-size-xs);
  margin-top: var(--spacing-xs);
}

.form-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 16px;
}

.owner-selection {
  position: relative;
}

.search-container {
  position: relative;
}

.dropdown-menu {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  background-color: white;
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-sm);
  z-index: 10;
  max-height: 200px;
  overflow-y: auto;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dropdown-item {
  padding: 8px 16px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.dropdown-item:hover {
  background-color: var(--primary-color-light);
  padding-left: 20px;
}

.dropdown-item.disabled {
  color: var(--text-secondary);
  cursor: not-allowed;
}

.dropdown-item.selected {
  background-color: var(--success-color-light);
  color: var(--success-color);
  font-weight: 500;
}

.dropdown-item.selected:hover {
  background-color: var(--success-color-light);
  color: var(--success-color);
  padding-left: 16px;
}

.selected-owner {
  margin-top: 8px;
  padding: 6px 12px;
  background-color: var(--success-color-light);
  color: var(--success-color);
  border-radius: var(--border-radius-sm);
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.selected-owner-info {
  margin-top: 8px;
  padding: 6px 12px;
  background-color: var(--primary-color-light);
  color: var(--primary-color);
  border-radius: var(--border-radius-sm);
  font-size: var(--font-size-sm);
}

.department-config {
  margin-top: 20px;
  background-color: #fafbfc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e1e8ed;
}

.department-header {
  margin-bottom: 28px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 28px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 50%, #f093fb 100%);
  border-radius: 16px;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.25), 0 4px 12px rgba(0, 0, 0, 0.1);
  color: white;
  position: relative;
  overflow: hidden;
}

.department-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(45deg, rgba(255, 255, 255, 0.1) 0%, transparent 50%, rgba(255, 255, 255, 0.1) 100%);
  opacity: 0;
  transition: opacity 0.3s ease;
}

.department-header:hover::before {
  opacity: 1;
}

.department-header .btn {
  padding: 12px 24px;
  font-weight: 700;
  border-radius: 12px;
  box-shadow: 0 4px 8px rgba(255, 255, 255, 0.2);
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  background: rgba(255, 255, 255, 0.15);
  border: 2px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
  position: relative;
  overflow: hidden;
}

.department-header .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
  transition: left 0.5s ease;
}

.department-header .btn:hover:not(:disabled) {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 15px rgba(255, 255, 255, 0.3);
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.5);
}

.department-header .btn:hover:not(:disabled)::before {
  left: 100%;
}

.department-header .btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.empty-departments {
  text-align: center;
  padding: 40px 24px;
  color: var(--text-secondary);
  font-style: italic;
  background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
  border-radius: 12px;
  border: 2px dashed #dee2e6;
  margin: 20px 0;
  position: relative;
}

.empty-departments::before {
  content: '📋';
  font-size: 48px;
  display: block;
  margin-bottom: 16px;
  opacity: 0.6;
}

.department-row {
  display: grid;
  grid-template-columns: 1fr 1fr auto;
  gap: 28px;
  padding: 28px;
  background: linear-gradient(135deg, #ffffff 0%, #fafbfc 50%, #f0f4f8 100%);
  border: 1px solid #e2e8f0;
  border-radius: 16px;
  margin-bottom: 20px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05), 0 1px 3px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

.department-row::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 5px;
  height: 100%;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 50%, #667eea 100%);
  opacity: 0;
  transition: all 0.4s ease;
}

.department-row::after {
  content: '';
  position: absolute;
  top: -50%;
  left: -50%;
  width: 200%;
  height: 200%;
  background: radial-gradient(circle, rgba(102, 126, 234, 0.03) 0%, transparent 70%);
  opacity: 0;
  transition: opacity 0.4s ease;
  pointer-events: none;
}

.department-row:hover {
  border-color: #667eea;
  box-shadow: 0 12px 28px rgba(102, 126, 234, 0.15), 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-3px) scale(1.01);
}

.department-row:hover::before {
  opacity: 1;
  width: 6px;
}

.department-row:hover::after {
  opacity: 1;
}

.department-selection,
.owner-selection {
  display: flex;
  flex-direction: column;
  gap: 8px;
  min-width: 0;
}

.department-selection .form-label,
.owner-selection .form-label {
  font-weight: 600;
  color: #374151;
  font-size: 14px;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.department-selection .form-label::before {
  content: '🏢';
  font-size: 16px;
}

.owner-selection .form-label::before {
  content: '👤';
  font-size: 16px;
}

.row-actions {
  display: flex;
  align-items: flex-end;
  padding-bottom: 12px;
  justify-content: center;
}

.row-actions .btn {
  padding: 12px 20px;
  border-radius: 12px;
  font-weight: 600;
  font-size: 14px;
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 6px rgba(239, 68, 68, 0.2), 0 1px 3px rgba(0, 0, 0, 0.1);
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  border: none;
  color: white;
  position: relative;
  overflow: hidden;
}

.row-actions .btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.row-actions .btn:hover {
  transform: translateY(-2px) scale(1.05);
  box-shadow: 0 8px 15px rgba(239, 68, 68, 0.3), 0 4px 8px rgba(0, 0, 0, 0.15);
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
}

.row-actions .btn:hover::before {
  left: 100%;
}

.row-actions .btn:active {
  transform: translateY(-1px) scale(1.02);
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-label {
  font-weight: 600;
  color: var(--text-primary);
}

.info-value {
  color: var(--text-secondary);
}

.field-configs {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.field-config-item {
  padding: 16px;
  background-color: white;
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  transition: all 0.2s ease;
}

.field-config-item:hover {
  border-color: var(--primary-color);
  box-shadow: 0 2px 8px rgba(64, 169, 255, 0.1);
}

.config-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.config-name {
  font-weight: 600;
  color: var(--text-primary);
}

.config-code {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-family: var(--font-family-mono);
  background-color: var(--bg-light);
  padding: 2px 8px;
  border-radius: var(--border-radius-sm);
  display: inline-block;
  width: fit-content;
}

.config-description {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  line-height: 1.4;
}

.empty-configs {
  text-align: center;
  padding: 24px;
  color: var(--text-secondary);
  font-style: italic;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: var(--border-radius-md);
  border: 1px dashed var(--border-base);
}

.error-message {
  color: var(--danger-color);
  font-size: var(--font-size-xs);
  margin-top: 4px;
}

.mt-4 {
  margin-top: 24px;
}

/* 步骤指示器样式 - 简化版本 */
.steps-indicator {
  display: flex;
  align-items: center;
  margin-bottom: var(--spacing-lg);
  padding: var(--spacing-md);
  background-color: var(--bg-light);
  border-radius: var(--border-radius-md);
  justify-content: center;
  border: 1px solid var(--border-base);
}

.step {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--bg-white);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: 500;
  min-width: 200px;
  justify-content: center;
  border: 1px solid var(--border-base);
}

.step-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 28px;
  height: 28px;
  border-radius: 50%;
  background-color: var(--bg-light);
  color: var(--text-secondary);
  font-weight: 600;
  margin-right: var(--spacing-sm);
  font-size: var(--font-size-sm);
  transition: all 0.3s ease;
}

.step.active .step-number {
  background-color: var(--primary-color);
  color: white;
}

.step-text {
  font-size: var(--font-size-sm);
}

.step:hover:not(.active) {
  background-color: var(--bg-hover);
}

.step.active {
  background-color: var(--primary-color);
  color: white;
  border-color: var(--primary-color);
}

.step-arrow {
  margin: 0 var(--spacing-md);
  font-size: var(--font-size-base);
  color: var(--text-secondary);
  font-weight: bold;
}

/* 路由字段相关样式 */
.available-fields {
  margin-bottom: 20px;
}

.field-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 12px;
}

.field-card {
  display: block;
  padding: var(--spacing-md);
  background-color: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  cursor: pointer;
  transition: all 0.3s ease;
}

.field-card:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-sm);
  transform: translateY(-1px);
}

.field-checkbox {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.field-info {
  flex: 1;
}

.field-name {
  font-weight: 600;
  color: var(--text-primary);
  margin-bottom: 4px;
}

.field-code {
  font-size: var(--font-size-sm);
  color: var(--text-secondary);
  font-family: var(--font-family-mono);
  background-color: var(--bg-light);
  padding: 2px 8px;
  border-radius: var(--border-radius-sm);
  display: inline-block;
  margin-bottom: 4px;
}

.field-description {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  line-height: 1.4;
}

.selected-fields {
  min-height: 60px;
}

.selected-fields-container {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.route-field-item {
  display: flex;
  align-items: center;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--bg-white);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  transition: all 0.3s ease;
  position: relative;
}

.route-field-item:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-sm);
}

.route-field-item.dragging {
  opacity: 0.6;
  transform: scale(0.98);
}

.field-priority {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background-color: var(--primary-color);
  color: white;
  font-weight: bold;
  font-size: var(--font-size-sm);
  margin-right: 12px;
  flex-shrink: 0;
}

.field-details {
  flex: 1;
  min-width: 0;
}

.delete-btn {
  margin-left: 8px;
  padding: 4px 8px;
  font-size: var(--font-size-xs);
}

.drag-handle {
  margin-left: 8px;
  padding: 4px;
  cursor: grab;
  color: var(--text-secondary);
  font-size: var(--font-size-sm);
}

.drag-handle:active {
  cursor: grabbing;
}

.drag-tip {
  font-size: var(--font-size-xs);
  color: var(--text-secondary);
  text-align: center;
  margin-top: 8px;
  font-style: italic;
}

.empty-fields {
  text-align: center;
  padding: 24px;
  color: var(--text-secondary);
  font-style: italic;
  background-color: rgba(0, 0, 0, 0.02);
  border-radius: var(--border-radius-md);
  border: 1px dashed var(--border-base);
}

/* 按钮样式 */
.next-step-btn {
  margin-left: 8px;
}

.prev-step-btn {
  margin-right: 8px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%) !important;
  border-color: #cbd5e1 !important;
  color: #64748b !important;
  transform: none !important;
  box-shadow: none !important;
}

.btn.btn-primary:disabled {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%) !important;
  border-color: #cbd5e1 !important;
  color: #64748b !important;
}

.department-count {
  font-size: 12px;
  margin-left: 4px;
  opacity: 0.8;
}

/* 多选用户样式 */
.selected-owners {
  margin-top: 16px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 12px;
  border: 1px solid #bae6fd;
  box-shadow: 0 2px 8px rgba(14, 165, 233, 0.1);
  transition: all 0.3s ease;
}

.selected-owners:hover {
  box-shadow: 0 4px 12px rgba(14, 165, 233, 0.15);
}

.owners-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #bae6fd;
}

.owners-count {
  font-size: 14px;
  font-weight: 600;
  color: #0369a1;
  display: flex;
  align-items: center;
  gap: 6px;
}

.owners-count::before {
  content: '👥';
  font-size: 16px;
}

.owners-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.owner-tag {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
  border: 1px solid #0ea5e9;
  border-radius: 20px;
  font-size: 13px;
  box-shadow: 0 2px 4px rgba(14, 165, 233, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.owner-tag::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 3px;
  height: 100%;
  background: linear-gradient(180deg, #0ea5e9 0%, #0284c7 100%);
}

.owner-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(14, 165, 233, 0.2);
  border-color: #0284c7;
}

.owner-tag .owner-name {
  color: #0369a1;
  font-weight: 600;
  margin-left: 3px;
}

.btn-xs {
  padding: 4px 6px;
  font-size: 12px;
  line-height: 1;
  border-radius: 50%;
  min-width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #ef4444;
  border: none;
  color: white;
  font-weight: bold;
  transition: all 0.3s ease;
  box-shadow: 0 2px 4px rgba(239, 68, 68, 0.2);
}

.btn-xs:hover {
  background-color: #dc2626;
  transform: scale(1.1);
  box-shadow: 0 3px 6px rgba(239, 68, 68, 0.3);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    width: 95%;
    max-height: 90vh;
  }
  
  .form-grid {
    grid-template-columns: 1fr;
  }
  
  .department-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .steps-indicator {
    flex-direction: column;
    gap: 12px;
  }
  
  .step-arrow {
    transform: rotate(90deg);
    margin: 8px 0;
  }
  
  .field-grid {
    grid-template-columns: 1fr;
  }
}

/* 负责人下拉选择框样式 */
.owner-dropdown-container {
  position: relative;
}

.custom-dropdown {
  position: relative;
  width: 100%;
}

.custom-dropdown.disabled {
  opacity: 0.6;
  pointer-events: none;
}

.dropdown-search {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e8ed;
  border-radius: 10px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.dropdown-search::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s ease;
}

.dropdown-search:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
}

.dropdown-search:focus::before {
  left: 100%;
}

.dropdown-search:disabled {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  color: #64748b;
  cursor: not-allowed;
  border-color: #cbd5e1;
}

.dropdown-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 20px rgba(0, 0, 0, 0.05);
  max-height: 240px;
  overflow-y: auto;
  z-index: 1000;
  backdrop-filter: blur(8px);
  animation: dropdownSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.dropdown-menu::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, #3b82f6, transparent);
}

@keyframes dropdownSlideIn {
  from {
    opacity: 0;
    transform: translateY(-8px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid rgba(226, 232, 240, 0.5);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  font-weight: 500;
}

.dropdown-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(59, 130, 246, 0.1), transparent);
  transition: left 0.4s ease;
}

.dropdown-item:hover {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  color: #1e40af;
  padding-left: 20px;
  border-left: 3px solid #3b82f6;
}

.dropdown-item:hover::before {
  left: 100%;
}

.dropdown-item:last-child {
  border-bottom: none;
  border-radius: 0 0 10px 10px;
}

.dropdown-item:first-child {
  border-radius: 10px 10px 0 0;
}

.dropdown-item.no-results {
  color: #64748b;
  font-style: italic;
  cursor: default;
  text-align: center;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

.dropdown-item.no-results:hover {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: #64748b;
  padding-left: 16px;
  border-left: none;
}

.user-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  position: relative;
}

.user-name {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
  transition: color 0.3s ease;
}

.dropdown-item:hover .user-name {
  color: #1e40af;
}

.user-id {
  font-size: 12px;
  color: #64748b;
  opacity: 0.9;
  font-weight: 500;
  padding: 2px 8px;
  background: rgba(148, 163, 184, 0.1);
  border-radius: 6px;
  display: inline-block;
  width: fit-content;
  transition: all 0.3s ease;
}

.dropdown-item:hover .user-id {
  background: rgba(59, 130, 246, 0.1);
  color: #3b82f6;
}

.owner-dropdown-container .select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-sm);
  background-color: white;
  font-size: var(--font-size-sm);
  transition: all 0.2s ease;
}

.owner-dropdown-container .select:focus {
  outline: none;
  border-color: var(--primary-color);
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.owner-dropdown-container .select:disabled {
  background-color: var(--bg-disabled);
  color: var(--text-muted);
  cursor: not-allowed;
}

/* 只读字段样式 */
.readonly-field {
  padding: 12px 16px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border: 2px solid #e2e8f0;
  border-radius: 10px;
  color: #475569;
  font-size: 14px;
  font-weight: 500;
  min-height: 20px;
  display: flex;
  align-items: center;
  transition: all 0.3s ease;
}

.readonly-field:hover {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  border-color: #cbd5e1;
}

/* 部门下拉选择框样式 */
.department-dropdown-container {
  position: relative;
}

.department-dropdown-container .custom-dropdown {
  position: relative;
  width: 100%;
}

.department-dropdown-container .dropdown-search {
  width: 100%;
  padding: 12px 16px;
  border: 2px solid #e1e8ed;
  border-radius: 10px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
}

.department-dropdown-container .dropdown-search::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s ease;
}

.department-dropdown-container .dropdown-search:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1), 0 4px 12px rgba(59, 130, 246, 0.15);
  transform: translateY(-1px);
  background: linear-gradient(135deg, #ffffff 0%, #f0f9ff 100%);
}

.department-dropdown-container .dropdown-search:focus::before {
  left: 100%;
}

.department-dropdown-container .dropdown-search:readonly {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  cursor: pointer;
  border-color: #cbd5e1;
}

.department-dropdown-container .dropdown-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  border: 2px solid #e1e8ed;
  border-radius: 12px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1), 0 4px 20px rgba(0, 0, 0, 0.05);
  max-height: 240px;
  overflow-y: auto;
  z-index: 1000;
  backdrop-filter: blur(8px);
  animation: dropdownSlideIn 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
}

.department-dropdown-container .dropdown-menu::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, #10b981, transparent);
}

.department-dropdown-container .dropdown-item {
  padding: 12px 16px;
  cursor: pointer;
  border-bottom: 1px solid rgba(226, 232, 240, 0.5);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  position: relative;
  overflow: hidden;
  font-weight: 500;
}

.department-dropdown-container .dropdown-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(16, 185, 129, 0.1), transparent);
  transition: left 0.4s ease;
}

.department-dropdown-container .dropdown-item:hover {
  background: linear-gradient(135deg, #ecfdf5 0%, #d1fae5 100%);
  color: #065f46;
  padding-left: 20px;
  border-left: 3px solid #10b981;
}

.department-dropdown-container .dropdown-item:hover::before {
  left: 100%;
}

.department-dropdown-container .dropdown-item:last-child {
  border-bottom: none;
  border-radius: 0 0 10px 10px;
}

.department-dropdown-container .dropdown-item:first-child {
  border-radius: 10px 10px 0 0;
}

.department-dropdown-container .dropdown-item.no-results {
  color: #64748b;
  font-style: italic;
  cursor: default;
  text-align: center;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
}

.department-dropdown-container .dropdown-item.no-results:hover {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  color: #64748b;
  padding-left: 16px;
  border-left: none;
}

.department-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  position: relative;
}

.department-name {
  font-weight: 600;
  color: #1e293b;
  font-size: 14px;
  transition: color 0.3s ease;
}

.department-dropdown-container .dropdown-item:hover .department-name {
  color: #065f46;
}

/* 字段值配置样式 */
.field-value-config {
  margin-top: 12px;
  padding: 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border: 2px solid #bae6fd;
  border-radius: 12px;
  position: relative;
  overflow: hidden;
}

.field-value-config::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, #0ea5e9 0%, #0284c7 100%);
}

.field-value-title {
  font-size: 14px;
  font-weight: 600;
  color: #0369a1;
  margin-bottom: 12px;
  margin-left: 8px;
}

.field-value-item {
  margin-bottom: 16px;
  padding: 12px;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 8px;
  border: 1px solid rgba(14, 165, 233, 0.2);
}

.field-value-item:last-child {
  margin-bottom: 0;
}

.field-value-label {
  font-size: 13px;
  font-weight: 600;
  color: #0f172a;
  margin-bottom: 8px;
  display: block;
}

.field-value-input {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  margin-bottom: 8px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.field-value-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.field-processor-container {
  position: relative;
}

.field-processor-dropdown {
  position: relative;
  width: 100%;
}

.field-processor-search {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.field-processor-search:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.field-processor-search.error {
  border-color: #ef4444;
  box-shadow: 0 0 0 2px rgba(239, 68, 68, 0.1);
}

.field-processor-menu {
  position: absolute;
  top: calc(100% + 4px);
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  max-height: 200px;
  overflow-y: auto;
  z-index: 1000;
}

.field-processor-item {
  padding: 10px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f3f4f6;
  transition: background-color 0.2s ease;
}

.field-processor-item:hover {
  background-color: #f9fafb;
}

.field-processor-item:last-child {
  border-bottom: none;
}

.field-processor-selected {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px 12px;
  background: linear-gradient(135deg, #dbeafe 0%, #bfdbfe 100%);
  border: 1px solid #93c5fd;
  border-radius: 6px;
  margin-top: 8px;
}

.field-processor-name {
  font-weight: 500;
  color: #1e40af;
}

.field-processor-remove {
  background: #ef4444;
  color: white;
  border: none;
  border-radius: 50%;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.2s ease;
}

.field-processor-remove:hover {
  background: #dc2626;
  transform: scale(1.1);
}

.field-error-message {
  color: #ef4444;
  font-size: 12px;
  margin-top: 4px;
}

/* 字段配置提示样式 */
.field-config-hint {
  background: linear-gradient(135deg, #f0f8ff 0%, #e6f3ff 100%);
  border: 2px solid #b3d9ff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 20px;
  position: relative;
  overflow: hidden;
}

.field-config-hint::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 4px;
  height: 100%;
  background: linear-gradient(180deg, #1976d2 0%, #1565c0 100%);
}

.config-hint-text {
  margin: 0 0 12px 8px;
  font-size: 14px;
  color: #1565c0;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.config-hint-text::before {
  content: '💡';
  font-size: 16px;
}

.field-names {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  margin-left: 8px;
}

.field-name-tag {
  background: linear-gradient(135deg, #e3f2fd 0%, #bbdefb 100%);
  color: #1976d2;
  padding: 6px 12px;
  border-radius: 16px;
  font-size: 13px;
  font-weight: 600;
  border: 1px solid #90caf9;
  box-shadow: 0 2px 4px rgba(25, 118, 210, 0.1);
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.field-name-tag::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.4), transparent);
  transition: left 0.5s ease;
}

.field-name-tag:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(25, 118, 210, 0.2);
  border-color: #1976d2;
}

.field-name-tag:hover::before {
  left: 100%;
}

.field-hint {
  font-weight: normal;
  color: #666;
  font-size: 12px;
  margin-left: 4px;
}

/* 动态配置字段值容器样式 - 美化版本 */
.field-values-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.field-config-row {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.02);
  border: 1px solid #f1f5f9;
  transition: all 0.3s ease;
}

.field-config-row:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  border-color: #e2e8f0;
  transform: translateY(-1px);
}

.field-select {
  flex: 0 0 160px;
  padding: 10px 14px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.3s ease;
  box-sizing: border-box;
  font-weight: 500;
}

.field-select:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  background: white;
}

.field-value-row {
  display: flex;
  align-items: center;
  gap: 8px;
}

.field-value-input {
  flex: 1;
  padding: 10px 14px;
  border: 2px solid #e2e8f0;
  border-radius: 8px;
  font-size: 14px;
  background: linear-gradient(135deg, #ffffff 0%, #f8fafc 100%);
  transition: all 0.3s ease;
  box-sizing: border-box;
  font-weight: 500;
}

.field-value-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
  background: white;
}

.field-value-input:disabled {
  background: linear-gradient(135deg, #f1f5f9 0%, #e2e8f0 100%);
  color: #64748b;
  cursor: not-allowed;
  border-color: #cbd5e1;
}

.field-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d1d5db;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.field-input:focus {
  outline: none;
  border-color: #3b82f6;
  box-shadow: 0 0 0 2px rgba(59, 130, 246, 0.1);
}

.remove-field-btn {
  background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  color: white;
  border: none;
  border-radius: 8px;
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s ease;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(239, 68, 68, 0.2);
}

.remove-field-btn:hover {
  background: linear-gradient(135deg, #dc2626 0%, #b91c1c 100%);
  transform: scale(1.05) rotate(90deg);
  box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
}

.add-field-btn {
  background: linear-gradient(135deg, #10b981 0%, #059669 100%);
  color: white;
  border: none;
  padding: 10px 18px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 8px;
  align-self: flex-start;
  box-shadow: 0 2px 8px rgba(16, 185, 129, 0.2);
  position: relative;
  overflow: hidden;
}

.add-field-btn::before {
  content: '';
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
  transition: left 0.5s ease;
}

.add-field-btn:hover {
  background: linear-gradient(135deg, #059669 0%, #047857 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
}

.add-field-btn:hover::before {
  left: 100%;
}

.add-field-btn:active {
  transform: translateY(0);
}

/* 动态配置项样式 - 简化版本 */
.dynamic-field-configs {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-lg);
}

.dynamic-config-item {
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  overflow: hidden;
  background-color: var(--bg-white);
  box-shadow: var(--shadow-sm);
  transition: all 0.3s ease;
}

.dynamic-config-item:hover {
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
  border-color: var(--primary-color);
}

.config-card {
  background-color: var(--bg-white);
}

.config-header {
  background-color: var(--bg-light);
  padding: var(--spacing-md);
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid var(--border-base);
}

.config-index {
  font-weight: 600;
  color: var(--text-primary);
  font-size: var(--font-size-sm);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.config-index::before {
  content: '⚙️';
  font-size: 14px;
}

.remove-config-btn {
  background-color: var(--danger-color);
  color: white;
  border: none;
  border-radius: var(--border-radius-md);
  width: 28px;
  height: 28px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 14px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.remove-config-btn:hover:not(:disabled) {
  background-color: var(--danger-hover);
  transform: scale(1.05);
}

.remove-config-btn:disabled {
  background-color: var(--text-secondary);
  cursor: not-allowed;
  opacity: 0.6;
  transform: none;
}

.config-content {
  padding: var(--spacing-lg);
  background-color: var(--bg-white);
}

.field-group {
  margin-bottom: 16px;
}

.field-group:last-child {
  margin-bottom: 0;
}

.field-label {
  display: block;
  font-weight: 600;
  color: #374151;
  margin-bottom: 8px;
  font-size: 14px;
}

.processor-selector {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.selected-processor {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: var(--spacing-sm) var(--spacing-md);
  background-color: var(--bg-light);
  border: 1px solid var(--border-base);
  border-radius: var(--border-radius-md);
  transition: all 0.3s ease;
}

.selected-processor:hover {
  border-color: var(--primary-color);
  box-shadow: var(--shadow-sm);
}

.processor-name {
  font-weight: 500;
  color: var(--text-primary);
  display: flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.processor-name::before {
  content: '👤';
  font-size: 12px;
}

.remove-processor {
  background-color: var(--danger-color);
  color: white;
  border: none;
  border-radius: var(--border-radius-sm);
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  font-size: 10px;
  font-weight: bold;
  transition: all 0.3s ease;
}

.remove-processor:hover {
  background-color: var(--danger-hover);
  transform: scale(1.05);
}

.add-config-section {
  text-align: center;
  margin-top: var(--spacing-lg);
  padding: var(--spacing-lg);
  background-color: var(--bg-light);
  border-radius: var(--border-radius-md);
  border: 2px dashed var(--border-base);
  transition: all 0.3s ease;
}

.add-config-section:hover {
  border-color: var(--primary-color);
  background-color: var(--bg-hover);
}

.add-config-btn {
  background-color: var(--primary-color);
  color: white;
  border: none;
  padding: var(--spacing-sm) var(--spacing-lg);
  border-radius: var(--border-radius-md);
  font-size: var(--font-size-sm);
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-xs);
}

.add-config-btn:hover {
  background-color: var(--primary-hover);
  transform: translateY(-1px);
  box-shadow: var(--shadow-md);
}

.add-config-btn:active {
  transform: translateY(0);
}

.add-icon {
  font-size: 16px;
  font-weight: bold;
}

</style>